我正在运行我的expressjs应用程序,并尝试使用aws sdk v3将消息(字符串化对象)推送到队列(本地堆栈)中。
awslocal sqs create-queue --queue-name my-queue
“@aws-sdk/client-sqs”:“^3.428.0”
出现此错误,
^
语法错误:意外的标记'<', " 反序列化错误:要查看原始响应,请检查隐藏的 该对象上的字段 {error}.$response。 在 JSON.parse
app.js
const express = require("express");
const { SQS, SendMessageCommand } = require("@aws-sdk/client-sqs");
const app = express();
const port = 3000;
// Define the LocalStack SQS endpoint
const localStackEndpoint = "http://localhost:4566";
// Configure the SQS client
const sqs = new SQS({
region: "us-east-1", // Specify any region (LocalStack doesn't enforce region constraints)
endpoint: localStackEndpoint,
});
// Route to send a message to the SQS queue
app.post("/test", async (req, res) => {
try {
// Specify the URL of your LocalStack SQS queue
const queueUrl = `${localStackEndpoint}/000000000000/my-queue`;
// Define the message body
const messageBody = "Hello, LocalStack!";
// Create the SendMessageCommand
const sendMessageCommand = new SendMessageCommand({
QueueUrl: queueUrl,
MessageBody: messageBody,
});
// Send the message
const sendMessageResponse = await sqs.send(sendMessageCommand);
console.log("Message sent successfully:", sendMessageResponse);
res.send("Message sent successfully");
} catch (error) {
console.error("Error sending message:", error);
res.status(500).send("Error sending message");
}
});
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
docker-compose.yml
version: '3'
services:
localstack:
image: localstack/localstack
ports:
- '4566-4599:4566-4599'
- '8080:8080'
environment:
- SERVICES=sqs
- DEBUG=1
- DATA_DIR=/tmp/localstack/data
- PORT_WEB_UI=8080
volumes:
- '${TMPDIR:-/tmp/localstack}:/var/lib/localstack'
@aws-sdk/client-sqs
库正在使用 json 协议,但 localstack
直到最近才支持 SQS(请参阅此 PR)
更新您的 docker compose 以使用最新的 localstack Docker 映像
localstack/localstack:3.1.0
应该很可能解决您看到的错误
version: '3'
services:
localstack:
image: localstack/localstack:3.1.0
ports:
- '4566-4599:4566-4599'
- '8080:8080'
environment:
- SERVICES=sqs
- DEBUG=1
- DATA_DIR=/tmp/localstack/data
- PORT_WEB_UI=8080
volumes:
- '${TMPDIR:-/tmp/localstack}:/var/lib/localstack'