React Client Cors issue - reactjs

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();
});

Related

I have a cross-domain request problem about React

I have a problem. When I click the button, an error is reported on the page.
"Access to XMLHttpRequest at 'http://localhost:8000/hello' from origin
'http://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource."
Here is client code
function SendRequest() {
axios({
url: "http://localhost:8000/hello",
method: "GET",
}).then((res)=>
{
console.log(res);
});
}
Here is server code
app.use((ctx, next) => {
console.log("ASDFSFDSF");
createProxyMiddleware({
target: "http://localhost:8000",
changeOrigin: true
})
});
The server use koa framework
If you're using express as a backend framework you can install a CORS-Middleware (npm i cors in your backend directory) and use it as an active middleware (globally, so for every incoming request) by calling app.use(cors()) after importing it using const cors = require("cors").
See here for more information about express and CORS Middleware.
That's not a React problem. That's the back-end blocking the request to your app. Read more about CORS.

why does react.js when upload file return cors

const formData = new FormData();
formData.append("CustomerName", this.state.customerName);
formData.append("Email", this.state.email);
formData.append("Phone", this.state.phone);
formData.append("PageNumber", this.state.pagesNumber);
formData.append("Notes", this.state.notes);
formData.append("WritingConversionTypeId", this.state.writingConversionTypeId);
formData.append("WritingDocumentTypeId", this.state.writingDocumentTypeId);
formData.append("WritingTimePeriodId", this.state.writingTimePeriodId);
formData.append("files", 'null');
writingRequest.postwritingRequest(formData).then((res) => {
console.log(res);
});
when attach to headrs form data it return CORS
i'm using react.js and server side ASP.NET Core3.1...
and it works when removing the (Content-Type: multipart/form-data) from headers
it works in swagger
enter image description here
in
at React Service to Call Api
import http from "../../config/http";
import endPoints from "../endPoints";
const writingRequestUrl = endPoints.WRITING_REQUEST_ENDPOINT;
export default {
postwritingRequest(writingRequest) {
return http
.post(
writingRequestUrl,
writingRequest
, {
headers: {
'enctype': 'multipart/form-data',
"Content-Type": "multipart/form-data"
},
}
)
.then((res) => {
return res;
});
},
};
In StartUp
At ASP.NET CORE
ConfigureServices
//Enable CROS To allow access to the resource
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
}));
In Configure
app.UseCors("MyPolicy");
CORS has nothing to do with react, your browser prevents the call as the client runs on a different domain than your server. On production this is usually not an issue, since both are typically running on the same domain.
If you want to avoid CORS in development, the Create React App bundle comes with a proxy server, that appends the CORS header to all HTTP requests, as described in the documentation.
Simply add the URL to your api to your package.json like so:
"proxy": "www.url-to-your-api.com"
Then make sure to run all requests from your react app against absolute links, so instead of calling www.url-to-your-api.com/api/ you should simply use /api/, this will use the proxy in development and the regular route in production.

Deno Oak Disable Cors

I am trying to 'connect' my small React JS app with my Deno API backend on my local environment with fetch().
const apiUrl = `http://localhost:8000`;
try{
fetch(apiUrl)
.then((res) => res.json())
.then((repos) => {
console.log(repos);
setAppState({ loading: false, repos: repos });
});
}catch(err){
console.log(err);
}
My app is serving on localhost:3000 and my deno api on localost:8000.
However, I am having problem with CORS:
Access to fetch at 'http://localhost:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I tried some suggestions like:
add line '"proxy": "http://localhost:8000" to reactjs project packages.json'.
Or to add:
var options = {
method: 'get',
headers: {
"Access-Control-Request-Headers": "*",
"Access-Control-Request-Method": "*"
},
}
fetch(apiUrl, options)
Or to add:
fetch(apiUrl, {mode: 'no-cors'})
However, nothing works in my case. All the time getting the same error and some additional based on suggestions.
So,I need to disable CORS in my reactjs and deno api app to allow local dev communication between frontend and backend.
Solution in my case was pretty easy.
I had to import oakCors into my Deno API app.ts
import { oakCors } from "https://deno.land/x/cors/mod.ts";
after that, just add the excluded origin after app instantiation:
app.use(
oakCors({
origin: "http://localhost:3000"
}),
);
NOTE: I tried to set origin to origin: false and that did not work in my case.
For more options on Deno CORS here is a link: https://deno.land/x/cors
This works just fine:
app.use(oakCors({ origin: "*" }));
For me, I had to first pass oakCors configuration to the app and then the routes.
app.use(oakCors({
origin: 'http://localhost:4200',
optionsSuccessStatus: 200,
}));
app.use(router.routes());
placeapp.use(oakCors()) before your routes like this:
app.use(oakCors())
app.use(route.routes())
this is allow all CORS before to manage the routes

Express CORs policy preventing Apollo client from fetching from server

I'm running a react dev server on http://localhost:3000 and an express server on http://localhost:8080 and am using an Apollo Client to query the server. To enable session data to be passed from client to server I have added the credentials: "include" parameter when initializing the Apollo Client.
I've added the following line in my express server (before the routes are defined) to configure cors:
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
However, when executing queries, the following error is thrown:
Access to fetch at 'http://localhost:8080/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
Why is the header response showing up as *? Am I configuring CORs incorrectly or am I missing something else?
The problem I was running into here was that despite enabling CORS for express:
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
The GraphQL middleware was over-riding the setting. Make sure to pass the cors: false param as shown below if using an Apollo Server and associated middleware.
gqlServer.applyMiddleware({ app, path: "/graphql", cors: false });
This error is a CORS error generated by the browser. use npm install --save http-proxy-middleware in your front end and add setupProxy.js file in frontend/src/setupProxy.js
setupProxy.js
//run defferent ports for website and api server
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api/', { target: 'http://localhost:8080/' })); //make change as per your application (So you can access your data on http://localhost:8080/api/ )
};
Alternate solution
If you are using webpack dev server, here's another way to proxy requests without making changes on NodeJS. Adding this to package.json:
"proxy": "http://localhost:8080"
Should allow webpack to proxy requests made to http://localhost:3000 to http://localhost:8080.
But this would mean request will need to be made to http://localhost:3000 instead of http://localhost:8080.
Since you have credentials: true, you should include the credentials in your fetch call:
fetch(url, {
credentials: 'include'
})
or
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);
This will send the request with the headers set to Access-Control-Allow-Credentials: true
without this, it will be rejected.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials

Axios having CORS issue

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"

Resources