简体   繁体   English

客户端获取 POST Unexpected token < in JSON at position 0 在使用 JSON.parse 后

[英]client side fetch POST Unexpected token < in JSON at position 0 after using JSON.parse in express

I'm trying to send a simple object via a fetch request to my express server but I keep getting the error when trying to log it.我正在尝试通过获取请求向我的快速服务器发送一个简单的 object,但是在尝试记录它时我不断收到错误消息。

currently when I log req.body (if I have the header 'Content-Type': 'application/x-www-form-urlencoded') I get:目前当我登录 req.body (如果我有 header 'Content-Type': 'application/x-www-form-urlencoded')我得到:

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

how Can I extract the value from this object?如何从这个 object 中提取值? using JSON.parse(req.body) I get使用 JSON.parse(req.body) 我得到

Unexpected token < in JSON at position 0 

I also want to note that when I use the header { 'Content-Type': 'application/json'} req.body logs as {} in my index route.我还想指出,当我在索引路由中使用 header { 'Content-Type': 'application/json'} req.body logs as {} 时。

here is my app.js这是我的 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 (router) 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;



here is my client's post request这是我客户的发帖请求

<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>

While sending the fetch request, we need to strigify the body.在发送fetch请求时,我们需要对strigify进行触发。

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

Please use bodyParser in your index.js or wherever express Applicatio is initialized请在您的 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());

Then in your route然后在你的路线

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");
});

It seems body parser was not the issue, the object is logged as JSON already.似乎正文解析器不是问题,object 已经记录为 JSON。 I just needed to access the strings inside我只需要访问里面的字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM