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

迪伦

我正在尝试将数据从我的客户端传递到服务器端脚本,但是我的程序会回复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!');
      }); 

好吧,当我从以前的项目创建 react-native 应用程序时,我使用了该请求,并且效果很好,所以我认为我向服务器请求数据的方法没有问题

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

我研究了一下,看到有人说

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

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

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

{
    "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)
克里斯格86

您传递给 fetch 的数据必须是字符串化的,否则[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!');
  }); 

希望这可以帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

简单JSON意外令牌{位于位置> 1

SyntaxError:JSON中位置1处的意外令牌o

SyntaxError:JSON中位置1 EXPRESS处的意外令牌o

SyntaxError:Ajax请求中位置1处的JSON中的意外令牌o

未捕获的SyntaxError:JSON中位置1错误的意外令牌o错误

UnhandledPromiseRejectionWarning:语法错误:JSON中位置1处的意外令牌o

如何使用JavaScript在位置1的JSON中修复意外令牌o?

如何修复Uncaught SyntaxError:JSON中位置1处的意外令牌o

如何修复“ SyntaxError:JSON中位置1处的意外令牌o”

Json 响应“JSON 中的意外令牌位于位置 0”

JSON中位于位置0的意外令牌J

单元测试时出错:“未捕获(承诺)语法错误:位置1的JSON中的意外令牌o”

JSON解析错误-位置1的JSON中出现意外令牌o

Javascript JSON解析错误:JSON中位置1处出现意外令牌'

NPM安装错误:解析“”附近时,JSON中位置1处的意外令牌<

JSON 中位置 0 的意外令牌 A - 使用 POST 方法时遇到问题

.angular-cli.json'失败。请确保文件是有效的JSON。错误:> JSON中位于位置的意外令牌]

SyntaxError:JSON中的意外令牌e在JSON.parse(<anonymous>)位置1

Jinja Flask问题:Uncaught SyntaxError:意外令牌{在JSON.parse位置1的JSON中

如何修复“未捕获的SyntaxError:JSON中位置1的意外令牌L”

角度-JSON中位置1处的意外令牌x-响应以[

SyntaxError:位置JSON中的意外令牌T

JSON中位置4上的意外令牌<

意外的令牌 < JSON 中的位置 Ionic

语法错误:当获取 rails json 时,JSON 中的意外标记 o 在位置 1

“意外的令牌} JSON 中的位置 139”错误消息

网络错误:新ApolloError位置0的JSON中的意外令牌<

语法错误:JSON 中的意外标记 o 在角度位置 1

AJAX POST中的400错误的请求错误