我正在尝试用 $http.get()
替换我的 $.ajax
调用。当我尝试时,我收到 404 Not Found 错误。
这是 ajax 调用:
// ToDo: See if there is an $http.get equivalent. That way the callback doesn't have
// to be wrapped in $scope.apply().
$.ajax({
url: '/PrestoWeb/api/ping/responses/',
type: 'POST',
data: JSON.stringify(latestPingRequest),
contentType: "application/json",
success: function (responses) {
// do stuff
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
这是 $http 调用:
var config = {
url: '/PrestoWeb/api/ping/responses/',
method: 'POST',
data: JSON.stringify(latestPingRequest),
contentType: "application/json"
};
$http.get(config)
.then(function (response) {
// do stuff
}, function (response) {
alert(response);
});
ajax 调用有效。 http 调用则不然。两次调用中的 URL、类型和数据完全相同。我错过了什么?
最佳答案
在我看来,您遇到的问题是使用 $http.get
而不是 $http.post
。 $http 对象有一些常见 http 动词的辅助方法,例如$http.get、$http.post、$http.put 会将方法设置为简写名称。 post 的辅助方法需要三个参数、一个 url、您的数据和一个配置对象,因此您的调用如下所示:$http.post('/PrestoWeb/api/ping/responses/',latestPingRequest, config)
在您的情况下,您在 http 配置对象中指定 method: 'POST'
但随后使用 $http.get
方法,该方法将发出 get 请求而不是您在配置对象中指定的内容。
因为您在配置对象中指定了该方法,所以您可以只使用 $http(config)
并完全跳过辅助方法。实际上,我更喜欢这样做,因为您的完整请求是在配置对象中定义的,而不是在使用的配置对象和方法中定义的。辅助方法也都有不同的签名,这令人困惑。更容易坚持 $http(config) IMO
关于javascript - $.ajax 调用有效,$http.get() 无效(404,未找到),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34424968/