【问题标题】:<pre>SyntaxError: Unexpected token # in JSON at position 0<br> &nbsp; &nbsp;at JSON.parse<pre>SyntaxError: Unexpected token # in JSON at position 0<br>   在 JSON.parse
【发布时间】:2019-04-08 12:45:40
【问题描述】:

我正在运行这段 NodeJS 代码并测试登录功能:

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

问题是当我运行 POST 命令时:

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

我收到错误: SyntaxError: Unexpected token # in JSON at position 0
  在 JSON.parse

对我来说,JSON 看起来格式很好。可能与编码有关?!我在哪里做错了? 谢谢。

【问题讨论】:

标签: node.js


【解决方案1】:

我会将res.send(errcode) 更改为res.status(errcode)res#send 的文档说:

当参数为String时,该方法将Content-Type设置为“text/html”

【讨论】:

  • 谢谢。但同样,问题出在请求上。我仍然遇到同样的错误。而且我使用的不是 React,而是一个简单的 curl 命令。
  • 问题出在请求中,因为我无法从请求中提取任何正文。一旦我发送请求,代码就会失败。
  • 好的。非常感谢!这有帮助。用 Fiddler 就可以了。问题是卷曲..
【解决方案2】:

通过 res.status(errcode) 更改 res.send(errcode) 并在没有获取正文数据时使用

//解析应用程序/x-www-form-urlencoded

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

//解析应用程序/json

app.use(bodyParser.json())

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2022-01-04
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多