angularjs - 对 API 的跨源 Ajax 请求返回 500(内部服务器错误)响应

标签 angularjs http http-status-code-500

当我对 api 执行 GET 调用时,我收到错误响应“500(内部服务器错误)”。这是错误消息:

XMLHttpRequest cannot load http://10.10.14.188:4800/api/v1/healthMonitor/DeviceStatus. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.4.217' is therefore not allowed access. The response had HTTP status code 500.

…虽然我在 postman 那里尝试或使用 curl 命令时得到了回复。

在这个调用中,我必须在 header 中传递一个 id。这是代码:

this.getState = function () {
        return $http({
                method: 'GET',
                url: 'http://10.10.14.188:4800/api/v1/healthMonitor/DeviceStatus',
                headers: {'Jab_Device_id': '80f1374192a6d6eb9ebf48e2eba18366','Content-Type': 'application/json'}
                });
    };

此外,我尝试使用 Ajax,但我也遇到了同样的错误。这是代码:

$.ajax({
        url: 'http://10.10.14.188:4800/api/v1/healthMonitor/DeviceStatus',
        headers: {
          'Jab_Device_id':'80f1374192a6d6eb9ebf48e2eba18366'  
        },
        method: 'GET',
        withCredentials: true,
        success: function(data){
          console.log('succes: '+data);
        }
      });

最佳答案

var url = "http://10.10.14.188:4800/api/v1/healthMonitor/DeviceStatus";
$http({
    method: 'JSONP',
    url: url,
    headers: {'Jab_Device_id': '80f1374192a6d6eb9ebf48e2eba18366','Content-Type': 'application/json'}
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

CORS 是跨源资源共享,如果您尝试从一个域访问另一个域,则会出现此错误。

尝试使用 JSONP。在您的情况下,JSONP 应该可以正常工作,因为它只使用 GET 方法。

尝试这样的事情:

来自 this answer

但是,如果您无法执行所有其他操作,则可以访问其余 api 更新过滤器以启用 CORS 请求

关于angularjs - 对 API 的跨源 Ajax 请求返回 500(内部服务器错误)响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45752648/

相关文章:

javascript - ng-click 指令不调用 Controller 函数

java - 带有 Signpost 和 Apache Commons HTTP 的 OAuth

php - 在 Windows 上使用 Laravel 5.7 出现 500 服务器错误

javascript - 即使 Node 服务器成功运行,index.html 也不会加载

javascript - 如何从 AngularJS 中的当前时间中减去一些小时数

javascript - NgMap 设置标记颜色

javascript - Angular 1.4.3 中的 $http 简写和简写有什么区别?

c++ - 将 HTML 源代码读取为字符串

php - 如果sql记录存在则无法调用php函数

asp.net - Docker for Windows - 内部服务器错误