node.js - POST 400(错误请求)JSON 中位置 1 处出现意外标记 o

标签 node.js reactjs mongodb express post

我试图将数据从客户端传递到服务器端脚本,但我的程序回复 POST http://localhost:3005/v1/account/login 400 (Bad Request) ,但每当我在 postman 上尝试它时,它总是正常工作,

这是我使用 ReactJS 应用程序向 NodeJS 服务器请求发布数据的代码:

fetch(config.endPoint.login, {
        method: 'POST',
        headers: {"Content-Type": "application/json"},
        body: {
            username: this.state.username,
            password: this.state.password
        }
      }).then((response) => {
        if(response.error_code == 0) {
          console.log(response);

          this.props.history.push("/main");
        } else {
          alert('login failed!');
        }
      }).catch((err) => {
        console.log(err);
        alert('Error\nplease check your network connection and try agian!');
      }); 

嗯,当我从以前的项目创建 react native 应用程序时,我使用了该请求,并且它运行良好,所以我不认为我向服务器请求数据的方法有问题

这是我的 Controller ,用于处理该登录路由上的 api 请求

// '/v1/account/login'
api.post('/login', passport.authenticate(
    'local', {
        session: false,
        scope: []
    }
), generateAccessToken, respond);

这是我处理 api 请求和响应的中间件

let authenticate = expressJwt({secret: SECRET});

let generateAccessToken = ( req, res, next ) => {

req.token = req.token || {};
req.token = jwt.sign({
    id: req.user.id
}, SECRET, {
    expiresIn: TOKENTIME
});
   next();
}

let respond = (req, res) => {
    Account.findOne({_id: req.user._id}, (err, account) => {
        if(err) {
            res.send(err)
        }
        let user_token = sha256.x2(Math.floor(new Date() / 1000) + account._id + config.serverCode + config.serverKey)
        account.user_token = user_token;

        account.save(err => {
            if(err) {
                res.send(err);
            }

            res.status(200).json({
                status: 'success',
                error_code: 0,
                user_token: user_token,
                user_id: req.user._id,
                user: req.user.username,
                token: req.token
            });
        });
    });
}

然后,我遇到一个错误,说 Access to fetch at 'http://localhost:3005/v1/account/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

所以我研究并发现在我的 index.js 文件中编写这段代码

app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);

// Pass to next layer of middleware
next();
});

现在,我在显示 POST http://localhost:3005/v1/account/login 400 (Bad Request) 时遇到错误

我研究了一下,发现有人这么说

bad request means that you're trying to fetch data from request object using invalid keys. see here

但我看不到我传递的错误数据,

我使用 postman 以这种格式传递数据:

{
    "username": "yoyo929",
    "password": "12345678"
}

而且效果很好, 我的代码有什么问题吗?

我也在我的 Nodejs 终端上看到了这个错误

SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at parse (F:\project\galaxy\node_modules\body-parser\lib\types\json.js:89:19)
at F:\project\galaxy\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (F:\project\galaxy\node_modules\raw-body\index.js:224:16)
at done (F:\project\galaxy\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (F:\project\galaxy\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)

最佳答案

您传递来获取的数据必须是字符串化的,否则将传入类似 [object Object] 的内容:

fetch(config.endPoint.login, {
    method: 'POST',
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify({
        username: this.state.username,
        password: this.state.password
    })
  }).then((response) => {
    if(response.error_code == 0) {
      console.log(response);

      this.props.history.push("/main");
    } else {
      alert('login failed!');
    }
  }).catch((err) => {
    console.log(err);
    alert('Error\nplease check your network connection and try agian!');
  }); 

希望这有帮助!

关于node.js - POST 400(错误请求)JSON 中位置 1 处出现意外标记 o,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53340053/

相关文章:

javascript - 如何将现有的回调 API 转换为 promise ?

mongodb - 当并非所有字段都有值时加入字段

javascript - Mongodb geoNear 和组聚合

node.js - 在Azure中作为应用程序服务运行的node.js应用程序的暂存槽为我提供了EADDRINUSE

javascript - 调用 onSubmit 时,react-hook-form 不起作用

node.js - 我可以显示 npm 运行的扩展命令吗?

node.js - 在 Windows 8 上安装 phonegap 时出现问题 - 未满足的依赖性

javascript - NodeJS nTwitter 演示

javascript - 在宽度增加的元素中滚动时内容跳跃/不自然的移动

javascript - 使用 Webpack 编译 Sass(和本地范围类名)