首页 > 解决方案 > 客户端在 express 中使用 JSON.parse 后,在位置 0 处获取 POST Unexpected token <

问题描述

我正在尝试通过获取请求向我的快速服务器发送一个简单的对象,但是在尝试记录它时我不断收到错误消息。

目前,当我登录 req.body 时(如果我有标题 'Content-Type': 'application/x-www-form-urlencoded'),我得到:

req body is { '{"password":"dXGT2yY!@2eM6~h-"}': '' }

如何从这个对象中提取值?使用 JSON.parse(req.body) 我得到

Unexpected token < in JSON at position 0 

我还想指出,当我 { 'Content-Type': 'application/json'}在索引路由中使用标头 req.body 日志作为 {} 时。

这是我的 app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
const bodyparser = require('body-parser')
var logger = require('morgan');

var app = express();

app.use(bodyparser.urlencoded({extended: true}));  //include bodyparser
app.use(bodyparser.json());                        //include bodyparser

var indexRouter = require('./routes/index');

app.use(express.static("public"));



app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());


app.use('/', indexRouter);


module.exports = app;

index.js(路由器)

var express = require('express');
var router = express.Router();
const path = require('path');


router.post('/authenticate', function(req, res, next) {

  console.log('req body is',JSON.parse(req.body)) //getting error here when parsing
  res.send("passconfirmed");
});

module.exports = router;



这是我客户的发帖请求

<script type="text/javascript">
    $(function(){

        //show the modal when dom is ready
        $('#loginModal').modal('show');
    });

    async function postData(url = '') {

  const response = await fetch(url, {
    method: 'POST', 
    mode: 'no-cors', 
    cache: 'no-cache', 
    credentials: 'same-origin', 
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow',
    referrerPolicy: 'no-referrer',
    body: JSON.stringify({password: document.getElementById("passholder").value}) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

    document.getElementById("loginButton").addEventListener('click',function(){
      console.log('sending data',document.getElementById("passholder").value)
        postData('http://localhost:3000/authenticate' )      
            .then(data => {
                console.log('returned from server',data); // JSON data parsed by `response.json()` call
                if(data === "passconfirmed"){
                    $('#loginModal').modal('hide');
                }
            });
    })
</script>

标签: javascriptnode.jsjsonexpressfetch

解决方案


在发送fetch请求时,我们需要到strigify正文。

body: JSON.stringify({password: document.getElementById("passholder").value} ),

推荐阅读