(Angular4 / MEAN)将请求发送到空本体的本地API结果
我试图发布数据到一个项目的API,例如:
"data": { "title": "stack", "notes": "asdsad", "time": "19:02", "meridian": "PM", "type": "Education", "_id": "5a2f02d3bba3640337bc92c9", "days": { "Monday": true, "Tuesday": false, "Wednesday": false, "Thursday": false, "Friday": false, "Saturday": false, "Sunday": false } }
但是,使用HttpClient发布数据时
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."); });
我总是从API中的Items Controller得到Bad Request 400响应。
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"}) } }
我已经在我的app.js中设置了BodyParser
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
在快速控制台中,输出如下
_startTime: 2017-12-11T22:35:18.204Z, _remoteAddress: '::1', body: {}, secret: undefined, cookies: {}, signedCookies: {}, route: Route { path: '/', stack: [ [Object], [Object] ], methods: { post: true } } } {}
正如你所看到的,身体是空的,这是防止一个项目被创build。 我已经使用Postman进行了testing,发送url编码的表单数据和原始的JSON数据的post成功并返回200.但是,我永远不能得到应用程序的请求工作。
任何帮助表示赞赏,因为我一直在为此奋斗了几个小时。
this.http.post("http://localhost:3000/api/items", JSON.stringify(item) -----> convert JSON object to string ).subscribe(...);
基于你的服务器端代码,我相信它期望JSON对象而不是JSONstring,因此从你的客户端删除JSON.stringify(item))
,你的POST的主体应该是JSON对象。
- Angular2 + TypeScript + moment.js => locale并不都在那里(只是'en')
- 无法从另一个文件夹访问我的.scss软件包文件
- Meteor npm install从package.json安装错误的版本
- nodejs如何在其他文件中使用promise输出并修改它,然后返回它的值
- 无法迁移到angular度5angular度文件获取无效的错误
- 为什么具有真正Headless选项的Chrome 59-Beta无法使用量angular器?
- 如何使用Angular2路由
- 与前端和后端的错误沟通(Java – Angular)
- 如何在Angular CLI中configuration代理