angularJS $http.Post not working: Failed to load resource: Request header field 0 is not allowed by Access-Control-Allow-Headers

狂风中的少年 提交于 2020-01-06 10:53:45

问题


I'm using $http to post some data to my data base. Here is the documentation of the database. I use it on my terminal and it works.

Here's the error message I got from Safari's console:

1)Failed to load resource: Request header field 0 is not allowed by Access-Control-Allow-Headers. (seems to be sensed by the database)

2)XMLHttpRequest cannot load https://beta-api.mongohq.com/mongo/MyDId/myDatabse/collections/myCollection/documents. Request header field 0 is not allowed by Access-Control-Allow-Headers.

Here's my code:

factory.sendUrlTag = function(data){
        d = '{"document" : {"url_URL":"53738eef9256a31f4fdf6bf8","tag_Tag":"537375fc9256a31f4fdf6bf3"} }'

        return $http({
        url: 'https://beta-api.mongohq.com/mongo/MyDId/myDatabse/collections/myCollection/documents',
        method: "POST",
        data: d,
        headers: [
             {'Access-Control-Allow-Origin':'*'},
                  {'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept'},
            {'Content-Type': 'application/json'},
                {'Authorization' : 'api-key MyKey'}
                 ]
    })
    }

    return factory;
};

I didn't have " {'Access-Control-Allow-Origin':'*'}, {'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept'}," before, but I did some research after I got the error and added these. But it's still not working.

I do $http.get() in my app to the same database and it works.

This thing is driving me nuts.... Please help! Thank you all! :)


回答1:


Access-Control-Allow-Origin and friends are response headers, not request headers. It wouldn't make sense if Bob was responsible for granting Bob permission to Alice's system.

The server (https://beta-api.mongohq.com/mongo/MyDId/myDatabse/collections/myCollection/documents) has to send them, not the client.

Since you are making a cross-origin POST request, the server also needs to be able to respond to a pre-flight OPTIONS request.




回答2:


I found some way maybe able to get around the issue: Use this and here to get around the cross origin origin issue. And this to get around the localhost

It may work.

Another relative post.



来源:https://stackoverflow.com/questions/23664468/angularjs-http-post-not-working-failed-to-load-resource-request-header-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!