【发布时间】:2021-01-11 12:54:51
【问题描述】:
我正在尝试通过 HTML 页面中的脚本将长 json 作为发布请求发送:(数据来自文本框,它是正确的 json 数组)
<script>
/* UPDATE ORGANIZATION LIST*/
function updateOrgs () {
var data = $('#showOrgs').val();
$.ajax({
url : "http://localhost:8000/api/updateOrgs",
type: "POST", // data type (can be get, post, put, delete)
data : {json:JSON.parse(data)}, // data in json format
async : false, // enable or disable async (optional, but suggested as false if you need to populate data afterwards)
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)
}
});
}
</script>
我已将我的快递设置为:
const express = require('express');
var bodyParser = require('body-parser')
// initialize express
const app = express();
// body-parser
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({extended: false})
我在我的 node express 应用程序中使用 body-parser 来读取正文中的 json,例如:
app.post('/api/updateOrgs', jsonParser, (req, res)=> {
try {
console.log(req.body);
// send response
res.send('Successfully updated');
} catch (e) {
res.send(e);
}
});
问题是我的快递应用打印了一个空对象{}。那么是因为我发布的json文件很大吗?它在一个数组中有 64 个对象。
或者问题来自使用使用body-parser模块作为app.post('/api/updateOrgs', jsonParser, (req, res)=> {的express应用程序?
【问题讨论】:
-
您可能缺少 Content-Type: application/json 标头
-
对小json有用吗?
标签: javascript node.js json express body-parser