Express body-parser:位于0的JSON中的意外标记#

时间:2018-01-07 02:54:14

标签: javascript json polymer

我正在尝试使用Polymer登录用户数据。我让它与Postman合作,但我在将其翻译成Polymer时遇到了麻烦。

在Postman中,它返回一个JSON对象,但在Polymer中它返回undefined。

聚合物客户端代码[连接到node.js服务器]

<iron-ajax id="ajaxUser"
  url="http://localhost:8080/login"
  method="post"
  handle-as="json"
  content-type="application/json"
  headers='{"Access-Control-Allow-Origin": "*"}'
  params="[[params]]"
  on-response="saveUserCredentials"
  last-response="{{user}}"></iron-ajax>

...

<paper-input id="username"></paper-input>
<paper-input id="password"></paper-input>
<paper-button on-tap="loginUser"></paper-button>

...

loginUser() {
  this.params = {"username": this.$.username.value, "password": this.$.password.value};
  console.log(this.params); // logs this.params as populated JSON 
  let request = this.$.ajaxUser.generateRequest();
  request.completes.then(req => {
    console.log(req);       // no log
    console.log(this.user); // no log
  })
}

saveUserCredentials() {
  console.log(this.user);
}

服务器

// Middleware
app.options('*', cors(corsOptions)) // preflight OPTIONS; put before other routes
app.use(formData.parse(formBody))   // parse req.body data from `express-form-data` module
app.use(bodyParser.json())
app.use(apiLimit)                   // Rate limit applied to all requests, can apply to specific endpoints
app.use((req, res, next) => {       // Enable Cross-Origin Resource Sharing (CORS)
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, content-type, Accept, Authorization, x-api-key")
  next()
}) 

错误

  

SyntaxError:位于0的JSON中的意外标记#   在JSON.parse()
  at createStrictSyntaxError(C:\ node_modules \ body-parser \ lib \ types \ json.js:157:10)
  at parse(C:\ node_modules \ body-parser \ lib \ types \ json.js:83:15)
  在C:\ node_modules \ body-parser \ lib \ read.js:121:18
   在invokeCallback(C:\ node_modules \ raw-body \ index.js:224:16)
  完成后(C:\ node_modules \ raw-body \ index.js:213:7)
  在IncomingMessage.onEnd(C:\ node_modules \ raw-body \ index.js:273:7)
  在IncomingMessage.emit(events.js:159:13)
  at endReadableNT(_stream_readable.js:1062:12)
  at process._tickCallback(internal / process / next_tick.js:152:19)

Dev Tools

1 个答案:

答案 0 :(得分:2)

问题是您的POST正文是空的(如请求有效负载的屏幕截图所示)。您正尝试通过<iron-ajax>.params传递用户凭据,该凭据旨在扩充URL查询参数(请注意请求URL如何包含用户凭据作为参数)。

要设置POST正文,请设置<iron-ajax>.body(并将this.params更改为this.body):

<iron-ajax body="[[body]]" ...>

demo