Search code examples
javascriptjsonpolymer

Express body-parser: Unexpected token # in JSON at position 0


I am trying to return user data from a login with Polymer. I have it working with Postman, but am having trouble translating it into Polymer.

In Postman this returns a JSON object, but in Polymer it is returning undefined.

Polymer Client Code [Connecting to node.js server]

<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);
}

Server

// 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()
}) 

Error

SyntaxError: Unexpected token # in JSON at position 0
at 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)
at C:\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\node_modules\raw-body\index.js:224:16)
at done (C:\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\node_modules\raw-body\index.js:273:7)
at 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


Solution

  • The problem is your POST body is empty (as seen in the screenshot of your request payload). You're attempting to pass the user credentials via <iron-ajax>.params, which is intended to augment the URL query parameters (notice how the request URL contains the user credentials as parameters).

    To set the POST body, set <iron-ajax>.body (and change this.params to this.body) instead:

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

    demo