POST 400(错误请求)位置1上的JSON中的意外令牌o

时间:2018-11-16 14:44:17

标签: node.js reactjs mongodb express post

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

这是我的代码,用于使用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!');
      }); 

好吧,当我从以前的项目中创建一个本机应用程序时,我会使用该请求,并且它运行良好,所以我认为我向服务器请求数据的方法并不存在问题

这是我的控制器,用于处理该登录路由上的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)

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

  

错误请求意味着您正在尝试使用无效键从请求对象中获取数据。 see here

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

我使用邮递员以以下格式传递数据:

{
    "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)

1 个答案:

答案 0 :(得分:4)

您传递给获取的数据必须进行字符串化处理,否则将传递诸如[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!');
  }); 

希望这会有所帮助!