我正在尝试通过 jQuery 对远程服务进行身份验证。首先,我确认我可以在浏览器之外执行此操作:
curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":"...","password":"..."}' http://example.com/auth
这会成功返回一个 token 。
现在我用 jQuery 试试:
$.ajax({
url: "http://example.com/auth",
type: "POST",
dataType: "json",
contentType: "json",
data: {username:"...",password:"..."},
error: function(data){alert(JSON.stringify(data))},
success: function(data){alert(JSON.stringify(data))}
});
我收到服务器错误 (500)。显然我做错了什么。这是我第一次尝试在 jQuery 中执行 POST,所以我不知道如何确定问题所在。我在这里做错了什么?
附言如果我已经有 token ,我可以通过 jQuery 成功执行 GET 请求:
$.ajax({
url: "http://example.com/stuff?token=f42652adcbfe3ed9d59fae62b5267b8d",
type: "GET",
dataType: "json",
error: function(data){alert(JSON.stringify(data))},
success: function(data){alert(JSON.stringify(data))}
});
最佳答案
我唯一注意到的是数据表示的不同。查看原始请求中的数据:
-d '{"username":"...","password":"..."}'
以及AJAX请求中的数据:
data: {username:"...",password:"..."}
前者将键用字符串包装起来,而后者则没有。整个东西也应该是一个字符串。尝试:
data: '{"username":"...","password":"..."}'
这会更符合 JSON formatted data总的来说,我相信。如果不将键包装在字符串中,它可能是一个 JavaScript 对象,但它不是 JSON 数据。
关于javascript - 我的 jQuery POST 请求有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19865694/