[英]Ajax POST request to Restheart MongoDB service
I am attempting to POST to a Restheart/MongoDB server using jQuery/ajax with some difficulty. 我正在尝试使用jQuery / ajax到一些困难地发布到Restheart / MongoDB服务器。 The response returned is as if I ran a GET and not a POST. 返回的响应就像我运行了GET而不是POST。 And it also appears that it is trying to execute the response as if it were a callback. 而且似乎它正在尝试执行响应,就好像它是回调一样。 I am guessing that is because I am using jsonp (?). 我猜这是因为我正在使用jsonp(?)。 But if I don't use jsonp, I get a CORS error (my db server is different from my development computer). 但是,如果我不使用jsonp,则会收到CORS错误(我的数据库服务器与开发计算机不同)。 But I have my header set for Allow-Origin: *. 但是我为Allow-Origin设置了标题:*。 Thoughts? 有什么想法吗?
myHeaders = {"Authorization":"Basic " + 'user:password'.toString('base64'),
"Content-Type":"application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*"
}
$.ajax({
method: "POST",
crossDomain: true,
contentType: "application/json",
headers: myHeaders,
dataType : 'jsonp',
jsonp: 'jsonp', // mongod is expecting the parameter name to be called "jsonp"
url: "http://mydomain:80/db/people",
data: JSON.stringify({ "name": "John", "location": "Boston" }),
success: function (data) {
console.log('success' + data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error', errorThrown);
}
})
Here is a screenshot of the error from Firefox when I try a GET request. 这是当我尝试GET请求时来自Firefox的错误的屏幕截图。 You can see I am passing the appropriate headers (I believe). 您可以看到我正在传递适当的标题(我相信)。
you should not use JSONP with RESTHeart, since it supports CORS. 您不应该将JSONP与RESTHeart一起使用,因为它支持CORS。
try (I haven't tried the code...) 试试(我还没有尝试代码...)
var myHeaders = {"Authorization":"Basic " + 'user:password'.toString('base64'),
"Content-Type":"application/json; charset=utf-8" };
$.ajax("http://mydomain:80/db/people", { method: "POST",
crossDomain: true,
contentType: "application/json",
headers: myHeaders,
dataType : 'json',
jsonp: false,
data: JSON.stringify({ "name": "John", "location": "Boston" })
})
.done(function( data, textStatus, jqXHR ) { console.log(textStatus) }))
.fail(function( jqXHR, textStatus, errorThrown ) { console.log('error', textStatus) });
The problem is with header 问题出在头上
var myHeaders = {"Authorization":"Basic " + 'user:password'.toString('base64'), "Content-Type":"application/json; charset=utf-8" };
Use btoa() function of javascript to convert to string to base64. 使用javascript的btoa()函数将字符串转换为base64。
btoa("userid:password")
So, final header string will loog like 因此,最终的标头字符串会像
var myHeaders = {"Authorization":"Basic " + btoa("userid:password"), "Content-Type":"application/json; charset=utf-8" };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.