我有一条路由,用于发布新的“ post”资源。在此路由中,我使用AWS开发工具包将项目放入DynamoDB中。如果使用AWS API进行的此操作遇到错误,我想将错误消息从服务器传播到客户端。但是,当我尝试执行此操作时,我只会收到一条错误消息,内容为“错误错误:[对象响应]”。
这是路线。
router.post('/', authMiddleware, async (req, resp) => {
let reqBody = req.body;
let imagePath;
if (reqBody.imageUrl) {
imagePath = reqBody.imageUrl;
} else {
let path = req.file.path;
console.log(path);
imagePath = path.substring(path.indexOf('/'), path.length);
console.log(imagePath);
}
let newPost = {
'id': uniqid(),
'title': reqBody.title,
'description': reqBody.description,
'date': new Date(),
'text': reqBody.text,
'country': reqBody.country,
'imageUrl': imagePath
};
let params = {
TableName: table,
Item: newPost
};
console.log("Adding a new item...");
console.log(params)
docClient.put(params, function (err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
resp.status(400);
resp.send(err.message);
return;
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
resp.sendStatus(200);
return;
}
})
})
这是客户端(create-posts.js)的POST请求
fetch('/posts', {
method: 'POST',
body: data
}).then((response) => {
console.log(response.text()); // line 23
console.log(response.statusText); // line 24
console.log(response.status); // line 25
if(response.status === 400) {
console.log('Received 400.'); // line 27
throw new Error(response);
}
return response.text();
}).then((data) => window.history.go()
).catch((err) => alert(`Error ${err}`));
发出此POST请求时,在控制台中看到以下内容:
[Error] Failed to load resource: the server responded with a status of 400 (Bad Request) (posts, line 0)
[Log] Promise {status: "pending"} (create-post.js, line 23)
[Log] Bad Request (create-post.js, line 24)
[Log] 400 (create-post.js, line 25)
[Log] Received 400. (create-post.js, line 27)
最后,我还收到一条警告消息,内容为“错误错误:[对象响应]”。
但是,如果查看服务器端日志,则会看到一条有用的错误消息:
"Unable to add item. Error JSON: {
"message": "One or more parameter values were invalid: An AttributeValue may not contain an empty string"}
我想要做的是将此错误消息从服务器传递到客户端。谁能帮助Javascript / Node / Express noob弄清楚这一点?