简体   繁体   English

使用Express JS发布时出错

[英]Error when doing post with express JS

I am testing the post method to create a todo item as follows. 我正在测试post方法来创建待办事项,如下所示。 I am using postman in chrome to simulate the post method call. 我在chrome中使用邮递员来模拟post方法调用。 However, it does not work and gives me the below error. 但是,它不起作用,并给我以下错误。 I suspect something is wrong with the way body-parser library is working. 我怀疑主体解析器库的工作方式有问题。 What am I doing wrong here? 我在这里做错了什么?

在此处输入图片说明

1  SyntaxError: Unexpected token b
2:    at parse (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/lib/types/json.js:83:15)
3:    at /Users/zack/mydrive/proj/express-demo/node_modules/body-parser/lib/read.js:116:18
4:    at invokeCallback (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:262:16)
5:    at done (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:251:7)
6:    at IncomingMessage.onEnd (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:308:7)
7     at IncomingMessage.emit (events.js:104:17)
8     at _stream_readable.js:908:16

Code: 码:

var express = require('express');
var app = express();
var handlebars = require('express-handlebars');
var bodyParser = require('body-parser');

//MIDDLEWARE
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}));

// TODOS
var todos = [
  { body: "take out the trash",completed: false},
  { body: "Do the laundry",completed:true},
  { body: "Make a screencast",completed:false}
]

app.post('/todos', function (req, res){
  console.log("todo:", req.body);
  var todo = req.body;
  console.log("todo:"+todo);
  todos.push(todo);
  res.status(200).json(todo);
  res.send('OK')
})

Further I observe that the problem is because of this line. 此外,我观察到问题出在此行上。

app.use(bodyParser.json());

Are you sure you are sending the request as JSON? 您确定要以JSON格式发送请求吗? Make sure you've selected it in Postman - https://imgur.com/j0M7TEX . 确保已在Postman- https: //imgur.com/j0M7TEX中选择了它。

If that didn't work, you can try the following - 如果那没有用,您可以尝试以下方法-

... ...

app.post('/todos', function (req, res){
  console.log("todo:", req.body);
  var todo = req.body;
  console.log("todo:"+todo);
  todos.push(todo);

  // Only try to send a single response.
  res.json(todo);
});

It looks like you were trying to send two responses, one containing JSON, and another with text/plain ('Ok'). 看来您正在尝试发送两个响应,一个包含JSON,另一个包含文本/纯文本('Ok')。

http://expressjs.com/fr/api.html#res.json http://expressjs.com/fr/api.html#res.json

It seems like your program is trying to interpret the post data as json data - and generating an error when it trys to parse the request data which is probably url-encoded. 似乎您的程序正在尝试将post数据解释为json数据-并在尝试解析可能是url编码的请求数据时生成错误。

Perhaps consider sending your data in json format. 也许考虑以json格式发送数据。 You will have to set the request headers to indicate the datatype is json. 您将必须设置请求标头以指示数据类型为json。 See this answer for an example: 请参见以下答案以获取示例:

Angular JS POST request not sending JSON data Angular JS POST请求未发送JSON数据

I just created a new session in postman and it started working. 我刚刚在邮递员中创建了一个新会话,它开始工作。 I am not sure if there is a caching effect but it works now. 我不确定是否有缓存效果,但现在可以使用。 I did not make any code change at all. 我根本没有进行任何代码更改。 Posting this as the solution now. 现在将其发布为解决方案。

Just don't put quotes on your JSON value. 只是不要在JSON值上加上引号。

Not "okay2" but just okay2 . 不是“ okay2”,而是okay2

I think that postman adds the quotes himself if needed and in this case creates ""okay2"" which isn't valid JSON. 我认为邮递员会根据需要自己添加引号,在这种情况下,将创建无效的JSON“ okay2”。

By the way you can test by clicking on the "row" radio button and write your own JSON. 顺便说一下,您可以通过单击“行”单选按钮进行测试并编写自己的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM