Is there any alternative to CORS google chrome extension? How to make successful ajax request without using CORS?

折月煮酒 提交于 2019-12-01 14:06:09

This problem usually related with the backend server, but if you don't have an access to the server so you have two options

First option to use this chrome extension: Allow-Control-Allow-Origin but unfortunately this extension is not available in the other browsers so you need to use

Second option by using online CORS proxy like

https://cors-anywhere.herokuapp.com/http://example.com

http://cors-proxy.htmldriven.com/?url=http://www.htmldriven.com/sample.json

CORS proxy is a free service for developers who need to bypass same-origin policy related to performing standard AJAX requests to 3rd party services.

Here's an example of Axiox call using CORS proxy

const urlProxy = 'https://cors-anywhere.herokuapp.com/http://example.com';
export function post() {
    let users = {
        username: '',
        password: '',
    };
    return axios({
            method:'POST',
            url:urlProxy,
            data: users, // Delete it if you dont have a data
            withCredentials: true, // Delete it if your request doesn't required credentials
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
                'Origin': '*',
                'Access-Control-Allow-Headers': '*',
                'Access-Control-Allow-Origin': '*',
            }
        })

            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            })
}

I added withCredentials() it makes your browser include cookies and authentication headers in your XHR request. If your service depends on any cookie (including session cookies), it will only work with this option set.

There's a Firefox extension that adds the CORS headers to any HTTP response working on the latest Firefox (build 36.0.1) released March 5, 2015 Check out this link

Hope this will help you

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