我正在尝试访问一个在json中响应的外部API。但是,如果将contentType设置为json,则会收到CORS错误。将dataType设置为jsonp可解决cors错误,我从服务器收到200响应,但浏览器无法解析数据,就像在json中一样。我遇到了parseerror。
我的代码如下。
$(document).ready(function() {
$('#sub').click(function() {
var dataString = JSON.stringify({
"user": {
"email": "myemail@somedomain.com",
"password": "password"
},
"request_type": "json"
});
var headerString = JSON.stringify({
"Content-Type": "application/json",
"cache-control": "no-cache",
"Postman-Token": "c971bb25-b44d-4529-b090-494ac62f5a68"//changed while posting this question
});
$.ajax({
type: "post",
url: "http://mywebsite.com/api/users/sign_in",
//contentType: 'application/jsonp;
charset=utf-8',
data: dataString,
dataType: 'jsonp',
headers: headerString,
cache: false,
success: function(result){
console.log(result);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
});