我正在尝试将数据发布到Items API,例如:
this.http.post("http://localhost:3000/api/items",
JSON.stringify(item))
.subscribe(
(val) => {
console.log("POST call successful value returned in body",
val);
},
response => {
console.log("POST call in error", response);
},
() => {
console.log("The POST observable is now completed.");
});
但是,使用HttpClient发布数据时
exports.createItem = async function(req, res, next){
// Req.Body contains the form submit values.
console.log(req);
console.log(req.body);
var item = {
id: req.body.id,
title: req.body.title,
days: req.body.days,
notes: req.body.notes,
time: req.body.time,
meridian: req.body.meridian,
type: req.body.type,
completed: req.body.completed,
}
try{
// Calling the Service function with the new object from the Request Body
var createdItem = await ItemService.createItem(item)
return res.status(201).json({status: 201, data: createdItem, message: "Succesfully Created Item"})
} catch(e){
console.log(e);
//Return an Error Response Message with Code and the Error Message.
return res.status(400).json({status: 400, message: "Item Creation was Unsuccesfull"})
}
}
我总是从API中的Items Controller获得Bad Request 400响应。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
我已经在我的app.js中设置了BodyParser
_startTime: 2017-12-11T22:35:18.204Z,
_remoteAddress: '::1',
body: {},
secret: undefined,
cookies: {},
signedCookies: {},
route:
Route {
path: '/',
stack: [ [Object], [Object] ],
methods: { post: true } } }
{}
在快速控制台中,输出如下
ListMultiMap
正如您所看到的那样,正文是空的,这阻止了某个项目的创建。我已经使用Postman测试了这一点,当发送url编码的表单数据和原始JSON数据时,帖子成功并返回200.但是,我永远无法获得应用程序的工作请求。
任何帮助都表示赞赏,因为我已经在这几个小时内一直在努力。
答案 0 :(得分:1)
this.http.post("http://localhost:3000/api/items",
JSON.stringify(item) -----> convert JSON object to string
).subscribe(...);
根据您的服务器端代码,我认为它需要JSON对象而不是JSON字符串,因此从客户端删除JSON.stringify(item))
,POST的主体应该是JSON对象。