javascript - 客户端在 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>
解决方案
在发送fetch
请求时,我们需要到strigify
正文。
body: JSON.stringify({password: document.getElementById("passholder").value} ),
推荐阅读
- c++ - 将整数类型转换为枚举:函数转换与初始化
- go - 将通道参数传递给golang中的动态加载函数
- javascript - Javascript 代码返回 Unhandled Promise Rejection: AbortError: The operation was aborted
- c# - 如何为 UWP Windows 10 安装实体框架和 SQLite?
- javascript - 将 C# DateTime 推送到 JavaScript 数组
- electron - 无法运行 Electron 应用程序 - EINVAL:无效参数,lstat
- c - 打印给定文本文件中出现频率最高的单词,无法在 C 中按频率排序
- javascript - 正则表达式接受字符串前后的空格
- string - 在 Cloudformation YAML 中,在多行字符串中使用 Ref(?使用 Fn:Sub)
- python - 如何编写 python pre-push 来检查提交信息?