繁体   English   中英

Web API的$ http角向给出XMLHttpRequest错误-请求的资源上没有'Access-Control-Allow-Origin'标头

[英]Angular $http to Web Api gives error of XMLHttpRequest -No 'Access-Control-Allow-Origin' header is present on the requested resource

我已经阅读了许多关于Angular $ http数据服务调用另一个应用程序Web Api的问题和解答。 是的,我看到有人说允许使用“邮递员”的原因是因为它类似于第三方外部应用程序等。

过去,我确实控制过安装了CORS等的Web Api。

但是,我认为某些事情必须是可能的,因为几个stackoverflow问题和答案确实的确给我带来了希望

这是错误

XMLHttpRequest cannot load http://localhost:60127/api/Product/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:60128' is therefore not allowed access.

带有Web Api代码的项目

 public class ProductController : ApiController
 {
    // GET api/<controller>
    public IHttpActionResult Get() {
    IHttpActionResult ret = null;
    // ....
 }

Web api的URL(与Postman一起使用) http:// localhost:60127 / api / Product /

角度代码

function productList() {
            //http://localhost:60127/api/Product/
            //dataService.get("/api/Product")
            dataService.get("http://localhost:60127/api/Product/")
                .then(function (result) {
                    vm.products = result.data;    // result is an http status
                    debugger;   // stop to see the code 
                },
                function (error) {
                    handleException(Error);

                });

        }

在WebAPiConfig类中,您需要在注册WebAPiConfig时启用Cors

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*"));

    }
}

如果服务器和客户端的来源不同,则需要在服务器端将Access-Control-Allow-Origin标头设置为true,

response.getHttpHeaders().add("Access-Control-Allow-Origin", "*"); //将禁止所有API发出请求

因此,如果您使用过滤器,则可以这样做

 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);

}

您启用了CORS吗? 并添加如下内容:

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ProductController : ApiController
{
   .....
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM