ajax向nodejs服务器发送JSON数组以删除密钥
决心!请参阅本文底部的解决方案…我已经在这个问题上纠缠了大约两天了,现在我开始意识到这一点。我试图将一个Json数组发布到我的节点服务器(跨域)并将其插入到cloudant数据库中。这个问题更多的是关于如何以正确的格式传递json。以下是我的客户端json和ajax:ajax向nodejs服务器发送JSON数组以删除密钥,ajax,json,node.js,post,express,Ajax,Json,Node.js,Post,Express,决心!请参阅本文底部的解决方案…我已经在这个问题上纠缠了大约两天了,现在我开始意识到这一点。我试图将一个Json数组发布到我的节点服务器(跨域)并将其插入到cloudant数据库中。这个问题更多的是关于如何以正确的格式传递json。以下是我的客户端json和ajax: function stress(){ var start = new Date().getTime(); $.ajax({ type: 'POST', url: 'url/', crossDomain: t
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
}];
My 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,我读取了它,这意味着它已经是一个对象,但我无法以任何方式访问数据(data[0]、data.name、data[0].name,服务器端没有任何内容)。我还尝试过以不同的方式从客户端发送json(在ajax-data:json.stringify({prod:products})中),但仍然没有成功
让服务器端的json(与上面的产品相同)以正确的顺序插入文档,问题是当我通过ajax post向跨域服务器发送相同的json时。我无法获取该json。任何想法或帮助都将不胜感激,谢谢
解决方案:
最后,我将对象放入另一个数组中,并使用该数组发送到服务器。这是客户端的工作ajax,请注意数据:{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]
在服务器/app.js中包含这一点也很重要扩展:true部分很重要
我是ajax新手。请检查这是否有帮助。我想我有一个类似的问题,现在已经解决了 请看我贴的答案
如果要在将json数据发送到节点服务器之前对其进行字符串化,请仅重试
data:products
您还需要节点模块body parser
使用它,您将能够通过ajax访问发布的数据,请参见答案使用:contentType:“application/json;charset=utf-8”
Hi-strustmaster你的意思是用application/json-application/x-www-form-urlencoded替换这一部分吗?我认为没有x-www-form-urlencoded,restful调用将无法工作!顺便说一句,restful调用与发送数据的编码无关,与实际资源无关。我没有使用过Node,但我很确定它无法使用内容类型标题中提到的百分位编码来解码JSON数据。哦,另外,我看到您正在尝试进行跨域请求。我希望您的节点服务器已为此进行了设置。我刚刚试着替换x-www-form-urlencoded,帖子将失败嗯:(是的,我的节点服务器设置为接受跨域请求,这一部分还可以。嘿,谢谢,在将json组成第二个数组并在没有stirngify的情况下发送数据后,解决了我的问题。
app.use(bodyParser.urlencoded({ extended: true }));