weixin_33724059 2016-03-12 15:40 采纳率: 0%
浏览 810

http服务器上的CORS失败

I am using a simple http-server while developing a javascript app in which there are with several ajax requests to external APIs. I started the server with "http-server --cors" via CLI, but still get "No 'Access-Control-Allow-Origin' header is present on the requested resource" errors. This occurs whether or not the external API requires a user key/pre-flight, such as:

var url = "http://api.rgrta.com/";
$.ajax({
    url: url,
    beforeSend: function(xhrObj){
        xhrObj.setRequestHeader("api_key","d4f...3f5");
    },
    type: "GET",
    dataType: "json"
})
.done(function(jsonData) {
    console.log("*** ajax success ***");
    callbackFunc();

    function callbackFunc() {
        console.log("callbackFunc");
    }
});

I've seen solutions involving express app.js configurations. Is node/express the only way to define request headers properly? What is the best way to set up my local http-server when developing for CORS-enabled API calls?

  • 写回答

2条回答 默认 最新

  • 撒拉嘿哟木头 2016-03-12 16:00
    关注

    That's not a server side code snippet which you have provided, rather its client side code which runs over browser, and hence cross origin errors would occur if the target api has cors turned off, the solution in that case would be to use a proxy.

    Also enabling cors on simple http server means that you are allowing your website content to be accessed elsewhere by others.

    评论

报告相同问题?