【发布时间】:2015-02-09 12:19:10
【问题描述】:
已解决!请参阅这篇文章底部的解决方案......我已经在这个问题上停留了大约 2 天,它开始影响到我。我正在尝试将 Json 数组发布到我的节点服务器(跨域)并将其插入到 cloudant 数据库中。这个问题更多的是关于以正确的格式获取 json。这是我的客户端 json 和 ajax:
function stress(){
var start = new Date().getTime();
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: JSON.stringify(products),
dataType: 'json',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
}
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
我的 Node.js 服务器端:
exports.create = function(req, res) {
var data = req.body;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
//var parsed = JSON.parse(data);
var msg = {};
for(product in data){
db.insert(data[product], function (err, body, headers) {
if (!err) {
msg.msg = 'success!';
console.log(JSON.stringify(msg);
}
else {
msg.msg = 'Error on insert, maybe the item already exists: ' + err
console.log(JSON.stringify(msg);
}
});
} }
我尝试了许多不同的方法。我基本上想要的是服务器端的一个对象,我可以遍历并插入到 cloudant 数据库中,每个对象都作为一个单独的文档。我尝试了许多 JSON.stringify 和 JSON.parse 的组合。使用 parse 没有运气,因为我收到错误提示 SyntaxError: Unexpected token o which I read 这意味着它已经是一个对象,但我无法以任何方式访问数据( data[0]、data.name、data[0] .name,服务器端什么都没有)。我也尝试过以不同的方式从客户端发送 json(在 ajax - data: JSON.stringify({prod:products}) 中,但仍然没有运气。
在服务器端(与上面的产品相同)有 json 以正确的顺序插入文档,问题是当我通过 ajax 帖子和跨域服务器发送相同的 json 时。我无法得到那个json。任何想法或帮助将不胜感激,谢谢
解决办法:
我最终将对象放入另一个数组并使用它发送到服务器。这是客户端的工作 ajax,请注意 data:{data:products} 这就是为我做的。下面还有产品 json 以及如何在 nodejs 服务器端访问它。
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: {data:products},
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
这是在服务器端访问它的方法。请记住,这仅适用于跨域 Post,但应该可以正常工作。
exports.create = function(req, res) {
var body = req.body;
//body.data[0] will get you the first object in the json, in this case it will be the war room table.
//If you use console.log to see it make sure you JSON.stringify(body.data[0]) or else you wil see [Object] [Object]
将它包含在你的 server/app.js 中也很重要 Extended: true 部分很重要。 Example
app.use(bodyParser.urlencoded({ extended: true }));
【问题讨论】:
-
使用:
contentType: "application/json; charset=utf-8" -
您好 Thrustmaster,您的意思是将此部分替换为 application/json - application/x-www-form-urlencoded。我认为如果没有 x-www-form-urlencoded,宁静的通话将无法正常工作
-
是的!顺便说一句,一个安静的调用与您发送的数据的编码无关,就像它与实际资源有关。我没有使用过 Node,但我很确定它无法使用 Content-Type 标头中提到的百分位数编码解码 JSON 数据。
-
哦,另外,我看到您正在尝试执行跨域请求。我希望你的 Node 服务器已经为它设置好了。
-
我刚刚尝试替换 x-www-form-urlencoded 并且 POST 会立即失败 :( 是的,我的节点服务器设置为接受跨域请求,这部分没问题。
标签: ajax json node.js post express