【问题标题】:client side fetch POST Unexpected token < in JSON at position 0 after using JSON.parse in express客户端在 express 中使用 JSON.parse 后,在位置 0 处获取 POST Unexpected token <
【发布时间】:2020-05-24 05:00:36
【问题描述】:

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

目前当我记录 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>

【问题讨论】:

  • 使用浏览器开发工具中的网络窗格检查响应正文。您可能会发现它是 HTML 文档而不是 JSON。也可能是 4xx 或 5xx 错误,而不是 200 OK 响应。
  • 你为什么使用JSON.parse(req.body)req.body 应该已经是一个对象了。
  • @sideshowbarker 我已经检查了网络面板,我只是收到一个请求失败的 500 错误。然后我将我的内容类型更改为 application/json 并从我的服务器中删除了 json.parse() 。然后我再次检查了网络面板,请求仍然处于未决状态,似乎没有超时,但是有效负载是正确的,但在记录 req.body.password 时在我的快速应用程序中显示为未定义
  • 我猜你在发送邮件时需要JSON.stringifybody?

标签: javascript node.js json express fetch


【解决方案1】:

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

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

【讨论】:

  • 谢谢,我错过了,但是在对数据对象 {'{"password":"whatever I send from client"}': '' },我已更新我的客户端代码以反映您的建议
【解决方案2】:

请在您的 index.js 或初始化 express Applicatio 的任何地方使用 bodyParser

const express = require('express');
const bodyParser = require('body-parser');


// create app by calling express()
const app = express();

// using the body parser
app.use(bodyParser.json());

然后在你的路线上

router.post('/authenticate', function(req, res, next) {
  const { password } = req.body;
  console.log('req body is', req.body);
  console.log('password is', password );
  res.send("passconfirmed");
});

【讨论】:

  • 是的,我在 app.js 文件中包含了 body-parser,所以这对我来说不是问题。正文解析器确实允许我记录 req.body,但是 req.body.password 将是未定义的
【解决方案3】:

似乎正文解析器不是问题,该对象已记录为 JSON。我只需要访问里面的字符串

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 2021-04-06
    • 2022-08-12
    • 2021-07-20
    • 2021-09-30
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多