【问题标题】:Angular http request get error: No 'Access-Control-Allow-Origin' header is [duplicate]Angular http请求获取错误:没有“Access-Control-Allow-Origin”标头是[重复]
【发布时间】:2015-11-09 01:48:02
【问题描述】:

当我向我的 api 发送请求时出现以下错误:

XMLHttpRequest cannot load http://api.myapp.example.com/v1/resources. No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://myapp.example.com' is therefore not allowed access.

据我所知,角度 http 请求不需要添加任何标头。为什么?看来我的网络知识不是。我不明白为什么会发生这个错误。如果您对这种情况有所了解,请帮助我。 我的查询:

$http.get('http://api.ingliz.tili.uz/v1/resources').success(function(data, status, headers) {
        console.log("success")
        console.log(data);
        console.log(status);
        $scope.resources = data
    }).error(function(data, status) {
        console.log("error")
        console.log(data);
        console.log(status);
    })

控制台中的请求:

General
    Remote Address:127.0.0.1:80
    Request URL:http://api.myapp.example.com/v1/resources
    Request Method:GET
    Status Code:200 OK
Response Header
    Connection:Keep-Alive
    Content-Length:240
    Content-Type:application/json; charset=UTF-8
    Date:Sun, 16 Aug 2015 08:04:08 GMT
    Keep-Alive:timeout=10, max=100
    Link:<http://api.myapp.example.com/v1/resources?page=1>; rel=self
    Server:Apache/2.4.10 (Win32)
    X-Pagination-Current-Page:1
    X-Pagination-Page-Count:1
    X-Pagination-Per-Page:20
    X-Pagination-Total-Count:1
Request Header
    Accept:application/json, text/plain, */*
    Accept-Encoding:gzip, deflate, sdch
    Accept-Language:en-US,en;q=0.8,ru;q=0.6,bg;q=0.4,zh-CN;q=0.2,zh;q=0.2,uz;q=0.2
    Cache-Control:max-age=0
    Connection:keep-alive
    Host:api.myapp.example.com
    Origin:http://myapp.example.com
    Referer:http://myapp.example.com/

我试过了:

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

但这是无奈之举。

【问题讨论】:

标签: angularjs http http-headers


【解决方案1】:

配置您的服务器以接受跨域请求

PHP

header("Access-Control-Allow-Origin: *");

ASP.NET Web API 2

1) 将 Microsoft.AspNet.WebApi.Cors NuGet 包添加到您的项目中。

2 ) 将此代码添加到您的配置中:

public static void Register(HttpConfiguration config)
{
    // New code
    config.EnableCors();
}

3) 将 [EnableCors] 属性添加到您的 Web API 控制器或控制器方法:

[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}

【讨论】:

    【解决方案2】:

    您必须在服务器端设置标头。

    如果您的服务器端在 php 中,请将此行添加到您的代码中:

    header("Access-Control-Allow-Origin: *");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-13
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 2018-09-19
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多