【发布时间】: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