Axios having CORS issue - reactjs

I added proxy in package.json and it worked great, but after npm run build the CORS issue has resurfaced again, does anyone know how to deal with CORS issue after npm run build in React.
I have tried to add headers in axios request using various methods. However, I failed to add 'Access-Control-Allow-Origin':'*' in axios request. My code is as follwing:
package.json
"proxy": {
"*":{ "target" : "http://myurl"}
}
GetData.js
axios.defaults.baseURL = 'http://myurl';
axios.defaults.headers.post['Content-Type'] ='application/json;charset=utf-8';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.get(serviceUrl, onSuccess, onFailure)
.then(resp => {
let result = resp.data;
onSuccess(result);
})
.catch(error => {
if(onFailure) {
return onFailure(error);
}
})
}
Note: It has enabled from server side, it is still not working.Currently, I can't change code from server side, My work is limited to client side only.

your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms

Just noting my solution for someone who might get here from googling. I resolved my CORS issue (when calling an external api from my UI in the browser) by setting withCredentials to false in my axios call:
axios({
method: 'get',
url: `https://api.someurl.com/subject/v2/resource/somevalue`,
withCredentials: false,
params: {
access_token: SECRET_TOKEN,
},
});
In this case, the external api's endpoint's security is based on the access_token.

May be helpful to someone:
I'm sending data from a react application to a golang server.
Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*"), the error was fixed.
React form submit function:
async handleSubmit(e) {
e.preventDefault();
const headers = {
'Content-Type': 'text/plain'
};
await axios.post(
'http://localhost:3001/login',
{
user_name: this.state.user_name,
password: this.state.password,
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
Go server got Router,
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", Login.Login).Methods("POST")
log.Fatal(http.ListenAndServe(":3001", router))
}
Login.go,
func Login(w http.ResponseWriter, r *http.Request) {
var user = Models.User{}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
err := json.Unmarshal(data, &user)
if err == nil {
user = Postgres.GetUser(user.UserName, user.Password)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(user)
}
}
}

I have encountered with same issue. When I changed content type it has solved. I'm not sure
this solution will help you but maybe it is. If you don't mind about content-type, it worked for me.
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';

This is happening because of restrict-origin-when-cross-origin policy.Browser sends a pre-flight request to know whom the API server wants to share the resources. So you have to set origin there in API server and send some status.After that the browser allow to send the request to the API server.
Here is the code.I am running front-end on localhost:8000 and api server is running on port 6000.
const cors = require("cors");
app.options("*", cors({ origin: 'http://localhost:8000', optionsSuccessStatus: 200 }));
app.use(cors({ origin: "http://localhost:8000", optionsSuccessStatus: 200 }));
I have set origin as my front-end url, If You set it to true , then it will allow only port 8000 to access rosource, and front-end running on port 8000 can not access this resource. Use this middleware before route in api server.

I had got the same CORS error while working on a Vue.js project. You can resolve this either by building a proxy server or another way would be to disable the security settings of your browser (eg, CHROME) for accessing cross origin apis (this is temporary solution & not the best way to solve the issue). Both these solutions had worked for me. The later solution does not require any mock server or a proxy server to be build. Both these solutions can be resolved at the front end.
You can disable the chrome security settings for accessing apis out of the origin by typing the below command on the terminal:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir="/tmp/chrome_dev_session" --disable-web-security
After running the above command on your terminal, a new chrome window with security settings disabled will open up. Now, run your program (npm run serve / npm run dev) again and this time you will not get any CORS error and would be able to GET request using axios.
Hope this helps!

This work out for me :
in javascript :
Axios({
method: 'post',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order
}).then(function (response) {
console.log(response.data);
});
and in the backend (.net core) :
in startup:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
and in controller before action
[EnableCors("AllowOrigin")]

CORS issue is something you will only encounter on a Broswer. It occurs beacuse the server does not allow request from others servers
i.e If I am sending request from http://localhost:3000 to any api(http://example.com/users) to get the user data from here.
If the server does not recognize your local host
#CrossOrigin(Origin = "*") // this will allow any request from any server you will not face CORS issue if you us this annotation
Now what if you are sending a request using axios in react to another sever which is not in your control the way to overcome that issue is by using http-proxy-middleware
npm i http-proxy-middleware // install this dependency
axios.{
method: 'post',
url: '/endpoint',
headers: {
'Content-Type': 'application/json',
},
proxy: createProxyMiddleware({
target: 'https://www.api.com',
changeOrigin: true}),
data: data
};
Now in this way a proxy request to www.api.com/endpoint will be sent and thus you will not recieve a cors issue
also add this in your package.json
"proxy": "https://www.api.com"

I come across this thread when having the same problem using Axios. What was not mentioned in the responses is that using fetch with no-cors mode can solve your issue.
Why ?
Apparently, Axios uses a XMLHttpRequest under the hood, not Request
and Axios fails because CORS is still being enforced and no-cors mode
is not supported.
Check this thread for more information

Please try this .. it worked for me
axios.get(`http://localhost:4000/api`,{ crossdomain: true }).then((result)=>{
console.log("result",result);
}).catch((error)=>{
console.log("Error",error);
});

Just simply add this to your headers
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
No need to use Access-Control-Allow-Origin : *

CORS issue can be simply resolved by following this:
Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"

Related

React Client Cors issue

I am learning react, I currently have a .net core API running in visual studio on localhost:7071.
The Local API is not running cors as there is no requirement for it to use Cors.
Creating a simple react client using the following will not return data due to a cors error?
I have tried a number of solutions online and none of them work, so how can I make this "simple" react client work without generating the following error
Access to XMLHttpRequest at 'http://localhost:7071/api/Users' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
function GetApiResults(){
const axios = require('axios').default;
axios.defaults.headers.common["Access-Control-Allow-Origin"] = "*";
axios({
method: 'get',
headers: { 'Content-Type': 'application/json' },
url: 'http://localhost:7071/api/Users',
}).then(function (response) {
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
export default GetResults;
You have a pretty straighforward description of the issue, browser expects the external resouces you are using (API in your case, external in terms it is not on same port) to provide CORS headers. If they are not set - browser will not execute the request. It will execute the request if you open the resource URL in browser tab, but if you are on localhost:3000 - any requests initiated by this page to anything that is not on localhost:3000 will require CORS to be set.
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0
Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading sensitive data from another site.
So either enable CORS support in your backend, either use CRA feature called Proxy: https://create-react-app.dev/docs/proxying-api-requests-in-development/
I prefer the manual proxy configuration, at the very end of the article.
Important: this proxy is for DEVELOPMENT only!
Here is a step-by-step instruction, just tested:
Install npm install http-proxy-middleware --save
Add src/setupProxy.js with content:
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/api",
createProxyMiddleware({
// I have a different port and Visual Studio might randomly change it
// Fix: edit running configuration
// https://stackoverflow.com/questions/70332897/how-to-change-default-port-no-of-my-net-core-6-api
// Notice: no /api at the end of URL, it will be added.
// more details at: https://www.npmjs.com/package/http-proxy-middleware
target: "https://localhost:7002",
changeOrigin: true,
// Im using .net core 6 starting api template
// which is running with a self-signed ssl cert with https enabled
secure: false
})
);
};
Modify your AXIOS configuration object to use new URL:
function GetApiResults() {
const axios = require("axios").default;
axios({
method: "get",
headers: { "Content-Type": "application/json" },
url: "/api/WeatherForecast"
})
/* ... */
}
Note: Im using default web api project, only changed [Route("api/[controller]")] (added api/) for Controller.
Restart the app and watch for logs from npm start output, proxy can log some errors there.
CORS is a browser feature. So, the browser you are using to access the React app must require you to use CORS. You need to setup CORS on your backend and allow connections from remote origin.
It will be good if you add CORS enabling code on Server Side. if your server-side app is in Express JS then add below middleware-
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Origin", "http://localhost:3000"); or add your react app url.
next();
});

.. from origin .. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I'm fairly new to making API requests. I'm am trying to set up an incoming slack webhook using a simple axios post request from my React project, however I keep receiving the CORS policy error. The request works perfectly in insomnia.
I'm using ngrok to expose my web server running on my local machine to the internet (I assumed this would correct the issue.) So I'm making the request from https://...ngrok.io, however I'm still receiving 'Status Code: 400' in my network tab along with the error above.
axios({
method: "post",
url:
"https://hooks.slack.com/services/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",
headers: { "Content-type": "application/json" },
data: { text: "Hello, World!" },
}).then(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
};
There are similar errors on stackoverflow, but none fix my error. I'd really like to understand why this is happening so any advice would be appreciated.
Fixed it, for those having the same issue:
What worked for me is setting Content-Type header to application/x-www-form-urlencoded. found it in this thread: https://github.com/axios/axios/issues/475 It appears that this triggers "simple request" and therefore avoids triggering CORS preflight. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

I can't perform a request from ReactJS. The header can not be written correctly

axios.get('http://localhost:8080/omp/patients', { headers: {authorization: 'Bearer ' + token}})
.then( response => {
this.state = response.data;
}
).catch(ex=> {
alert("You are not registered");
//console.log(e)
});
In network I have the field: "Access-Control-Request-Headers: authorization" but no field "authorization: token"
You will need to set the Authorization header correctly, as in the comment above.
For your reply about CORS Policy:
You will need to learn about CORS, but essentially Chrome and other browsers halt network requests if they do not have proper CORS headers set upon response. A preflight is an initial request that is sent to the same URL to learn whether the URL will support CORS, before sending the actual request. It looks like the server doesn't understand CORS preflights or isn't configured properly.
You have a couple options:
If you have access to the server configuration or code (such as a Laravel or NodeJS server), install a CORS plugin.
If you are the only user using this, you can install CORS browser extensions for Chrome or Firefox or whatever.
Change your code to this:
axios.get('http://localhost:8080/omp/patients', { headers: { "Authorization": 'Bearer ' + token}})
.then( response => {
this.state = response.data;
}
).catch(ex=> {
alert("You are not registered");
//console.log(e)
});
Also in you app.js/index.js where ever you are running your server import/require cors module and do like this:
let cors = require('cors');
app.use(cors());
Hope this helps!

missing token ‘x-auth’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel [duplicate]

This question already has an answer here:
Missing token in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel
(1 answer)
Closed 4 years ago.
i want to get data with post method from axios package and xampp sever,
i have an error when work with firefox :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/aftab/inventory3/v1/repository/all. (Reason: missing token ‘x-auth’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).[Learn More]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/aftab/inventory3/v1/repository/all. (Reason: CORS request did not succeed)
but when test it in chrome it work correctly and i don't have any error ,
my axios request code is:
let page = 1;
let config =
{
'Content-Type': 'application/x-www-form-urlencoded',
'x-auth': localStorage.getItem("token"),
};
let data = {page: page};
if (localStorage.getItem("token")) {
await axios({
method: "post",
url: "http://127.0.0.1/aftab/inventory3/v1/repository/all",
data: data,
headers: config
}).then(function (response) {
console.log(response);
}).catch(function (error) {
if (error.response) {
cosole.log(response);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
});
} else {
localStorage.removeItem("token");
// this.history.push('/log/in');
}
in the firefox console :
firefox console
in firefox console network, only option method was sent and after it we dont have any request but in the chrome it work correct and we have a post method request after option method
change your config to look like this
let config =
{
'Content-Type': 'application/x-www-form-urlencoded',
'x-auth': localStorage.getItem("token"),
'Access-Control-Allow-Origin': '*'
};
and also enable cors on your server
when we create a build from project this is work correctly in both chrome and firefox ,because in build edition of project option method don't send and we have only post method and it work on all browsers,It's like a bug in react
I have similar issue and checked my axios version and it was 0.18.0
POST request was working fine. However, GET request was not working with similar issue you have mentioned. Then I tried with beta version.
Try this beta version of axios ie 0.19.0-beta.1
https://github.com/axios/axios/tree/v0.19.0-beta.1
It fixes in my case.
"axios": "0.19.0-beta.1"
Note : if you plan to use beta version. I hope it should work.

React, Fetch-API, no-cors, opaque response, but still in browser memory

I've been trying to make an React site, which would fetch a GET-response from API and print it out to my .html-file. I've managed to fetch the file just right, but i can't access the JSON-data server sends me.
If i use no-cors in my Fetch-request, i get an opaque response containing pretty much nothing, but if i go to Developer tools i can find my data there and read it. If i do use cors, almost same thing. I get an 403-error, but my data is in the browser memory, but my code doesn't print it out. I can find the response from Network in developer tools.
Why does the server give me an error, but still i get my data? And how can i access it, if it's in the browser?
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {data2: []}
this.apihaku = this.apihaku.bind(this)
}
componentDidMount() {
this.apihaku(),
console.log("Hei")
}
apihaku () {
fetch('https://#######/mapi/profile/',
{method: 'GET', mode:'no-cors', credentials: 'include',
headers: {Accept: 'application/json'}}
).then((response) => {
console.log(response);
response.json().then((data) =>{
console.log(data);
});
});
}
render() {
return <div>
<button>Button</button>
</div>
}}
ReactDOM.render(
<Clock />,
document.getElementById('content')
)
EDIT: Error images after trying out suggestions
https://i.stack.imgur.com/wp693.png
https://i.stack.imgur.com/07rSG.png
https://i.stack.imgur.com/XwZsR.png
You're getting an opaque response, because you're using fetch with mode: 'no-cors'. You need to use mode: 'cors' and the server needs to send the required CORS headers in order to access the response.
Fetch is doing exactly what the documentation says it's supposed to do, from Mozilla:
The fetch specification differs from jQuery.ajax() in two main ways:
The Promise returned from fetch() won’t reject on HTTP error status
even if the response is an HTTP 404 or 500. Instead, it will resolve
normally (with ok status set to false), and it will only reject on
network failure or if anything prevented the request from completing.
By default, fetch won't send or receive any cookies from the server,
resulting in unauthenticated requests if the site relies on
maintaining a user session (to send cookies, the credentials init
option must be set). Since Aug 25, 2017. The spec changed the default
credentials policy to same-origin. Firefox changed since 61.0b13.
So you need to use CORS, otherwise you get an opaque response (no JSON), and then 403 to me suggests that you haven't authenticated properly. Test your API with Postman, if I had to take a guess I'd say the API isn't sending the cookie because it's a GET request, so no matter how well you set your headers on the client it won't work. Try it as a POST instead. GET requests should really only be used to drop the initial HTML in the browser. I think for your headers use these, include the creds that the API sends and allow the domain to be different.
mode: "cors", // no-cors, cors, *same-origin *=default
credentials: "include", // *same-origin
Try this and see where is the error happening i believe in the parsing but lets check and see
fetch(https://#######/mapi/profile/, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "include"
})
.then((response) => {
console.log(response);
try {
JSON.parse(response)
}
catch(err){
console.log("parsing err ",err)
}
})
.catch((err)=>{
console.log("err ",err)
});
I had a similar issue, this kind of problem happend when a HTTP port try to send request to a HTTPS endpoint, adding a "mode:'no-cors'" doesn't do what is SOUND doing but rathere when the documentation says.
I fixed the issue by allowing in my API Application for calls from my HTTP port
(i'm using a .net 6 as an API in debugging mode, my code look like this https://stackoverflow.com/a/31942128/9570006)

Resources