node.js - 将 Content-Type 设置为 json 但请求以 x-www-form-urlencoded 形式出现
问题描述
我正在使用 ajax 将帖子发送到我的应用程序。在邮递员中,一切都按预期工作,但是在浏览器中,数据进来了x-www-form-urlencoded
,数据丢失了。
下面是我的 ajax 和 postman 配置以及它们在 req 中的相应标题...
$.ajax({
url: '/',
headers: {
'Accept': 'application/json',
'Content-Type': "application/json"
}, // send as JSON
data: JSON.stringify(formData),
method: 'POST'
});
headers:
{ host: 'localhost:8080',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en-US,en;q=0.5',
'accept-encoding': 'gzip, deflate',
referer: 'http://localhost:8080/',
'content-type': 'application/x-www-form-urlencoded',
'content-length': '0',
connection: 'keep-alive',
'upgrade-insecure-requests': '1',
pragma: 'no-cache',
'cache-control': 'no-cache' }
headers:
{ data: '{"name":"tester", "email": "t@t.com", "message":"This is a test"}',
contenttype: 'application/json',
datatype: 'xml/html/script/json',
'cache-control': 'no-cache',
'postman-token': 'cbaa5cbe-0ab8-4328-abfd-f5dc6a6acd90',
'user-agent': 'PostmanRuntime/7.1.1',
accept: '*/*',
host: 'localhost:8080',
'accept-encoding': 'gzip, deflate',
'content-length': '0',
connection: 'keep-alive' }
还有我的相关服务器代码:
app.use(bodyParser.json());
//handle urlencoded data
app.use(bodyParser.urlencoded({extended:false}));
app.post('/', function (req, res) {
console.log(res);
console.log('----------------------------------------------------------');
console.log(req);
//var jsonData = JSON.parse(req.headers.data);
console.log(req.body);
console.log(req.data);
let transporter = courier.createTransport({...});
let mailOptions = {...};
transporter.sendMail(mailOptions, function (error, info) {
if (error)
console.log(error);
else
console.log('email sent:' + info.response);
});
res.render('index', {
title: 'Projects',
projects: projects
});
});
app.get('/', function (req, res) {
res.render('index', {
title: 'Projects',
projects: projects
});
});
请停下!
解决方案
你可以简单地:
JSON.parse(data)
在你
success: function(data){
var object =JSON.parse(data);
}
的 json 解析数据后,你可以做任何你喜欢的事情。
推荐阅读
- vue.js - JS/Vue:确认一个类是公共 API 的一部分?
- linux - 如何从 shell 脚本的命令输出中提取列值
- javascript - 悬停在导航项目上时CSS3轻微缩进
- sql - 使用 SQLite 对另一个表中的多个列使用一个查找表
- php - DI 构造函数支持多个不同的发布版本
- r - 向ggplot添加文本的问题
- c++ - 为什么 C++ 程序无法在 GCC 和 Clang 上编译?
- python - 使 Tab 键在文本框 tkinter 中执行 4 个空格而不是 8 个空格
- google-polyline - 渲染谷歌地图折线编码
- postgresql - 5:输入/输出错误错误:执行失败;`/bin/launchctl bootstrap gui/502 和 FATAL:用户的密码验证失败