<pre>SyntaxError: Unexpected token # in JSON at position 0<br/>    at JSON.parse

时间:2019-04-08 12:45:40

标签: node.js

I am running this block of NodeJS code and test the login functionality:

const express = require('express');
const bodyParser = require('body-parser');
let jwt = require('jsonwebtoken');
let config = require('./config');
let middleware = require('./middleware');

class HandlerGenerator {
   login (req, res) {
     let username = req.body.username;
     let password = req.body.password;
     // For the given username fetch user from DB
     let mockedUsername = 'admin';
     let mockedPassword = 'password';
     if (username && password) {
         if (username === mockedUsername && password === mockedPassword) {
            let token = jwt.sign({username: username}, 
                        config.secret, 
                        { expiresIn: '24h' // expires in 24 hours });
            // return the JWT token for the future API calls
            res.json({
               success: true,
               message: 'Authentication successful!',
               token: token
           });
         } else {
            res.send(403).json({
               success: false,
               message: 'Incorrect username or password'
            });
        }
    } else {
       res.send(400).json({
          success: false,
          message: 'Authentication failed! Please check the request'
       });
    }
 } 

 index (req, res) {
   res.json({
     success: true,
     message: 'Index page'
   });
}
}


// Starting point of the server
function main () {
let app = express(); // Export app for other routes to use
let handlers = new HandlerGenerator();
const port = process.env.PORT || 8000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes & Handlers
app.post('/login', handlers.login);
app.get('/', middleware.checkToken, handlers.index);
app.listen(port, () => console.log(`Server is listening on port: ${port}`));
}

main();

The problem is when i run the POST command:

curl --header "Content-Type: application/json" --request POST --data '{"password":"password", "username":"admin"}' http://localhost:8000/login

I get the error: SyntaxError: Unexpected token # in JSON at position 0
   at JSON.parse

To me thr JSON looks well formatted. Probably something to do with encoding?! Where am i doing mistake? thanks.

2 个答案:

答案 0 :(得分:0)

I would change res.send(errcode) by res.status(errcode), Documentation for res#send says:

When the parameter is a String, the method sets the Content-Type to “text/html”

答案 1 :(得分:0)

change res.send(errcode) by res.status(errcode) and use if you don't getting body data

// parse application/x-www-form-urlencoded

app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json

app.use(bodyParser.json())