Dealing with CORS in a create react app [duplicate] - javascript

I am trying to make an API call through Axios in my React Application. However, I am getting this CORS issue on my browser. I am wondering if i can resolve this issue from a client side as i dont have any access to the API internally. Attached is my code.
const response = axios({
method: "post",
dataType: "jsonp",
url: "https://awww.api.com",
data: {
appToken: "",
request: {
applicationName: "ddfdf",
userName: "jaime#dfd.com",
password: "dfd",
seasonIds: [1521ddfdfd5da02],
},
},
});
return {
type: SHARE_REVIEW,
payload: "response",
};
Attached is my WebPack.config.js
module.exports = {
entry: ["./src/index.js"],
output: {
path: __dirname,
publicPath: "/",
filename: "bundle.js",
},
module: {
loaders: [
{
exclude: /node_modules/,
loader: "babel",
query: {
presets: ["react", "es2015", "stage-1"],
},
},
{ test: /\.json$/, loader: "json-loader" },
],
},
resolve: {
extensions: ["", ".js", ".jsx"],
},
devServer: {
historyApiFallback: true,
contentBase: "./",
},
node: {
dns: "mock",
net: "mock",
},
};

the simplest way what I found from a tutorial of "TraversyMedia" is that
just use https://cors-anywhere.herokuapp.com in 'axios' or 'fetch' api
https://cors-anywhere.herokuapp.com/{type_your_url_here}
e.g.
axios.get(`https://cors-anywhere.herokuapp.com/https://www.api.com/`)
and in your case edit url as
url: 'https://cors-anywhere.herokuapp.com/https://www.api.com',

The ideal way would be to add CORS support to your server.
You could also try using a separate jsonp module. As far as I know axios does not support jsonp. So I am not sure if the method you are using would qualify as a valid jsonp request.
There is another hackish work around for the CORS problem. You will have to deploy your code with an nginx server serving as a proxy for both your server and your client.
The thing that will do the trick us the proxy_pass directive. Configure your nginx server in such a way that the location block handling your particular request will proxy_pass or redirect your request to your actual server.
CORS problems usually occur because of change in the website domain.
When you have a singly proxy serving as the face of you client and you server, the browser is fooled into thinking that the server and client reside in the same domain. Ergo no CORS.
Consider this example.
Your server is my-server.com and your client is my-client.com
Configure nginx as follows:
// nginx.conf
upstream server {
server my-server.com;
}
upstream client {
server my-client.com;
}
server {
listen 80;
server_name my-website.com;
access_log /path/to/access/log/access.log;
error_log /path/to/error/log/error.log;
location / {
proxy_pass http://client;
}
location ~ /server/(?<section>.*) {
rewrite ^/server/(.*)$ /$1 break;
proxy_pass http://server;
}
}
Here my-website.com will be the resultant name of the website where the code will be accessible (name of the proxy website).
Once nginx is configured this way. You will need to modify the requests such that:
All API calls change from my-server.com/<API-path> to my-website.com/server/<API-path>
In case you are not familiar with nginx I would advise you to go through the documentation.
To explain what is happening in the configuration above in brief:
The upstreams define the actual servers to whom the requests will be redirected
The server block is used to define the actual behaviour of the nginx server.
In case there are multiple server blocks the server_name is used to identify the block which will be used to handle the current request.
The error_log and access_log directives are used to define the locations of the log files (used for debugging)
The location blocks define the handling of different types of requests:
The first location block handles all requests starting with / all these requests are redirected to the client
The second location block handles all requests starting with /server/<API-path>. We will be redirecting all such requests to the server.
Note: /server here is being used to distinguish the client side requests from the server side requests. Since the domain is the same there is no other way of distinguishing requests. Keep in mind there is no such convention that compels you to add /server in all such use cases. It can be changed to any other string eg. /my-server/<API-path>, /abc/<API-path>, etc.
Even though this technique should do the trick, I would highly advise you to add CORS support to the server as this is the ideal way situations like these should be handled.
If you wish to avoid doing all this while developing you could for this chrome extension. It should allow you to perform cross domain requests during development.

Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.

Another way besides #Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.
A simpler way is to use express-http-proxy
run npm run build to create the bundle.
var proxy = require('express-http-proxy');
var app = require('express')();
//define the path of build
var staticFilesPath = path.resolve(__dirname, '..', 'build');
app.use(express.static(staticFilesPath));
app.use('/api/api-server', proxy('www.api-server.com'));
Use "/api/api-server" from react code to call the API.
So, that browser will send request to the same host which will be
internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)

You can have your React development server proxy your requests to that server. Simply send your requests to your local server like this: url: "/"
And add the following line to your package.json file
"proxy": "https://awww.api.com"
Though if you are sending CORS requests to multiple sources, you'll have to manually configure the proxy yourself
This link will help you set that up Create React App Proxying API requests

You can set up a express proxy server using http-proxy-middleware to bypass CORS:
const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname));
app.use('/proxy', proxy({
pathRewrite: {
'^/proxy/': '/'
},
target: 'https://server.com',
secure: false
}));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port);
console.log('Server started');
From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.
const URL = `/proxy/${PATH}`;
return axios.get(URL);

you must be missing Cors support on your server side code. In Asp.net core you can do it following way.
Add the following call in public void ConfigureServices(IServiceCollection services)
in Startup.cs file.
public void ConfigureServices(IServiceCollection services)
{
app.UseCors(options =>
options.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod());
}

I had the issue and I was in a dev environment (localhost) so my client and server origins where different...
so finally I overcame the problem by writing a simple custom proxy server that runs on localhost, (because I didn't had access to the server code, and I needed to allow cors from the responding origin)
Simple proxy server that runs on localhost:3001:
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
var cors = require("cors");
const app = express();
const corsOptions = {
// origin: ["http://localhost:3000"],
origin: true,
credentials: true,
};
app.use(cors(corsOptions));
const proxyMiddleware = createProxyMiddleware("/", {
target: "https://....api origin.....com",
changeOrigin: true,
});
app.use(proxyMiddleware);
app.listen(3001, () => {
console.log("proxy is listening on port 3001");
});
note that my react app is running on port 3000 and my proxy server is on port 3001
because we're using credentials in our request we need to also set origin to our app's origin to our white list, otherwise cors sets "Access-Control-Allow-Origin" to "*" which causes in-browser security error.
react sample login post request through my proxy:
axios.post("http://localhost:3001/Login", dataToPost, { withCredentials: true })
.then((res) => {
if (res.status === 200) {
//all cookies are set in you're browser
console.log(res);
}
})
.catch((err) => {
console.log(err);
});

If you trying to do something like fetch an 3rd party api and you're getting CORS error from the client-side, you can try to do using this extension:
Allow CORS: Access-Control-Allow-Origin
For chrome: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf
For mozilla: https://addons.mozilla.org/pt-BR/firefox/addon/access-control-allow-origin/

As #Nahush already pointed out, this is actually a server issue and not something that should be handled on the client side. The server is supposed to add the headers for Access-Control-Allow-Origin:
Reference - https://www.w3.org/wiki/CORS_Enabled#How_can_I_participate.3F
Here, I am just adding an easier way to do this on the server side if your server uses express framework. Using the express CORS Middleware is a 2 line code solution for this.
install using -
npm install -S cors
Add the following code to your backend app.
import cors from 'cors';
app.use(cors());
And done.

I did use 2 solutions to dealing with it:
Using http-proxy-middleware. However, please do following below steps on video, instead of read me of library, https://youtu.be/4B5WgTiKIOY . (I did mention the weakness if you use this solution also)
Use Firebase functions to create middleware, not too complicated. I will update detail then here also.
Please let me know if you have any question.

Related

HTTP requests in React app are not working over a network connection, but they are working on localhost

I’ve been building a React app for a while now and have been testing responsiveness across multiple devices.
The React app itself works perfectly fine on my local machine. When accessing the React instance over the network, all HTTP requests fail because it wants to send HTTP requests to port 3000 instead of port 5000 which is what my Node.js server is running on.
[1] Compiled successfully!
[1]
[1] You can now view client in the browser.
[1]
[1] Local: http://localhost:3000
[1] On Your Network: http://192.168.1.122:3000
[0] [nodemon] starting `node server.js`
[1] Compiled successfully!
[1] webpack compiled successfully
[0] Server is running on port 5000
[0] MongoDB Connected!
Example of a request in the React app
// Submit application to database
const storeAndSubmit = (formData) => {
try {
// eslint-disable-next-line
const res = axios({
method: 'post',
headers: {
'Content-Type': 'application/json',
},
url: 'http://localhost:5000/api/applications',
data: formData,
});
dispatch({
type: APPLICATION_SUCCESS,
payload: formData.pageNumber,
});
} catch (err) {
dispatch({
type: APPLICATION_FAIL,
});
}
};
Because I don’t know what IP address React will choose when running my start script, I can’t just hard code the IP address into the request. Is there a React environment variable that can be accessed that has the current local network IP address after the start script has been run? If so, I can use that in my HTTP requests and I think that might work.
Error example over the network
xhr.js:210 POST http://192.168.1.122:3000/api/applications 404 (Not Found)
One thing you can do is proxy your requests by adding the following to your package.json file: "proxy": "http://localhost:5000",
Now in your fetch or Axios calls you can use the following URL '/api/applications' instead of 'http://localhost:5000/api/applications'
You are having a networking issue, so let’s go over it in detail.
You have two processes running on your development machine:
a Node.js HTTP server serving the HTML file which loads the React app on localhost:3000. Let’s call this AppServerProcess
a Node.js HTTP server running a controller/driver for the database on localhost:5000. Let’s call this DbServerProcess
So what happens when you are requesting the web application from another device in the network?
The device will make an HTTP request to http://192.168.1.122:3000, where the AppServerProcess will handle the request and respond with the HTML content and the relevant scripts and assets, which will be loaded by the browser. The code in the JavaScript scripts (the web application), will have the fetch code with a URI of http://localhost:5000, which the device will resolve into itself, where it will fail to find anything.
Now, the computer running both processes (DbServerProcess and AppServerProcess) has at least one IP address on the local network, which is 192.168.1.122. This means that if the DbServerProcess is running on localhost:5000, it should also be available on 192.168.1.122:5000, so the URI that should be hardcoded on fetch is http://192.168.1.122:5000/api/applications.
Note that this will also work when working locally, as the IP address will resolve to itself.
Also note that if the computer running both processes has DHCP configured, this IP address may change subject to that configuration, where you seem to have a misconception of what is happening, because it’s not React that chooses that, and it’s not even the AppServerProcess; it’s the OS which has at least one network interface that has a local IP address assigned by the DHCP server running on the router. If you want this to be static, then that is an OS configuration (pretty straight forward on both Windows, macOS and Linux).
Look for "setting static IP address on {operating_system_name}".
I will assume if you specify the React port while starting your app, you will be able to solve this issue and correct me if I am wrong.
You can just do this on Linux:
PORT=3006 react-scripts start
Or this on Windows:
set PORT=3006 && react-scripts start
Check this answer.
Look into cors-npm for your backend server because that maybe the reason for not connecting.
Later you can maybe use Cloudflare Tunnel for your web server and use that address to access your web server in the react app. The link can be provided as an environment variable for the react. see setup react env variable
Firstly, test if the backend API is working or not via Postman.
http://192.168.1.122:5000/ should work on your case.
=========================================================
After it
Try this code on your frontend after checking the backend is working correctly with Postman.
const api = axios.create({
baseURL: "http://192.168.1.122:5000/api/", //PLEASE CONFIRM IP.
headers: {
'Content-Type': 'application/json',
},
});
const submitApi = async (formData) => api.post('/applications', formData);
const storeAndSubmit = async (formData) => {
try {
const {data} = await submitApi(formData);
if(!!data) {
dispatch({
type: APPLICATION_SUCCESS,
payload: formData.pageNumber,
});
} else {
dispatch({
type: APPLICATION_FAIL,
});
}
} catch(e) {
dispatch({
type: APPLICATION_FAIL,
});
}
}
I think you should check the response on the browser in the device you want to connect to the app from.
With the 404 code, the potential reason may be that the device and your computer are not using the same Wi-Fi modem.
You should not use a domain at all:
url: '/api/applications',
or
url: 'api/applications',
The former dictates api to be served from the domain's root, and the latter requires api to be served from the current page's path. In both cases, schema, domain, and port will be inherited from the current page's URL.
Details are in RFC 2396.
It allows you use your code without changes on any domain, any port, as the hosting architecture is not of the frontend app's concern.
Make a .env file and maybe try this:
REACT_APP_API_ENDPOINT=http://192.168.1.blablabla
You can also do:
"scripts" : {
"start": "REACT_APP_API_ENDPOINT=http://localhost.whatever npm/yarn start"
"start-production": "REACT_APP_API_ENDPOINT=http://production.whatever npm/yarn start"
}
It was taken from How can I pass a custom server hostname using React?.

Redirecting backend calls in Vue application

I am trying to deploy my website written in Vue to a static webhosting service (AWS S3).
I have been using the bencodezen boilerplate which seems to be generated using Vue-CLI. The boilerplate comes with a pre-configured development server such that you can redirect the backend calls (using axios) to either a mock backend or to a production backend:
vue.config.js
module.exports = {
[...]
// Configure Webpack's dev server.
// https://cli.vuejs.org/guide/cli-service.html
devServer: {
...(process.env.API_BASE_URL
? // Proxy API endpoints to the production base URL.
{ proxy: { '/api': { target: process.env.API_BASE_URL } } }
: // Proxy API endpoints a local mock API.
{ before: require('./tests/mock-api') }),
},
}
All calls to myurl.com/api/* will be directed to either the mocked backend or the API_BASE_URL if such is defined. This works fine while using the vue-cli-service serve development server but I'm failing to understand how to translate this to AWS S3, or any other webserver suited for production. If I try to make a login, post-request I get the following response from AWS:
405 Method Not Allowed
Indicating that the call was never redirected (AWS S3 doesn't allow POST calls).
Is it possible to redirect the API-calls directly from the web browser to the backend without going through the webserver? If not, how to I setup my production webserver in such a ways that the calls to myurl.com/api/* are automatically forwarded?
In the production environment (where devServer config does not apply) you need to manually handle the URLs, using some logic to figure out where the requests need to go. If the backend is not on the same host as the frontend, something like this:
const apiPath = process.env.NODE_ENV === 'development' ? '/api' : 'https://mybackendurl.com/api';
axios({
url: `${apiPath}/login`,
method: 'post',
headers: myHeaders,
// etc
})
You probably won't want to do that before every API call so I recommend making some sort of API service you can import and plug into axios. Then you can do something simple like url: API.Login()

Ionic React / Capacitor, requests work on web version and with postman but not on a device

I'm using axios to make requests to fetch the data from my external API (it's HTTP AWS server with ExpressJS and Nginx). I tested it on my local machine with the web version of my Ionic app and everything is working expected. Also I can fetch data if I'm using my phone's browser.
Same goes with postman, I can fetch data without any problems.
The only place where these requests don't work is the actual device. Looking at the Android Studio console the error is: "Msg: Network Error" (failing to figure out how to get more from axios error object).
I configured CORS following the official Ionic documentation. I've set all needed origins and options (can't use * origin because I have to use credentials with my requests). Express configuration looks like this:
const corsOptions = {
origin: [
'http://localhost:8100',
'http://localhost:8080',
'http://localhost',
'capacitor://localhost',
'ionic://localhost',
],
credentials: true,
optionsSuccessStatus: 200,
exposedHeaders: ["set-cookie"]
}
// Enable preflight requests for all routes
app.options('*', cors(corsOptions));
app.use(cors(corsOptions));
On the client (request example):
try {
const response = await axios('http://my.api.url', {
method: 'get',
withCredentials: true,
headers: {
'Accept': 'application/json'
}
});
const data = response.data;
// Do something with the data
} catch(error) {
console.log(error);
};
I think it has something to do with Capacitor, maybe there is a problem with non-https API (but then the question is why does it work with the web version). I tried disabling credentials for my requests but the error reoccur. Also removing Nginx doesn't seem to change anything.
Update: Also the axios says the request is sent but the server didn't respond.
I sorted it out, I had to do following.
Had to add a SSL to my web server (I used letsencrypt).
Had to add this to capacitor.config.json:
"server": {
"allowNavigation": [
"my.api.url"
]
}
Official Capacitor Documentation - Common Configuration

Angular 10 configure proxy from localhost to domain for fix CORS

I want make a GET request from my application angular to an API.
my application is on (localhost:4200).
When I request i use this URL
return this.http
.get<parameter>('https://sub.staging.company.com/application/action/getParams')
but I have a CORS errors like below :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
For avoid this error, I created a proxy.conf.js
const PROXY_CONFIG = [
{
context: ["/application/action"],
target: "https://sub.staging.company.com",
secure: false,
changeOrigin: true,
},
];
module.exports = PROXY_CONFIG;
But I have always this error and the proxy doesn't work.
How I can fix my problem ?
Thank for your help.
You need to proxy from a location on the same domain as your dev server. The browser still sees https://sub.staging.company.com/application/action/getParams as a cross domain request. You need to make a local call to /application/action/getParams and then the proxy will get it from https://sub.staging.company.com/
To facilitate your development locally and assuming you're using Google Chrome, a Chrome extension like this should do the trick.
Use have to implement it on backend too...
Like for node.js
npm i cors
then in index.js(root) file
const cors = require('cors');
const corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions);

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I'm running into an issue with my isomorphic JavaScript app using React and Express.
I am trying to make an HTTP request with axios.get when my component mounts
componentDidMount() {
const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders';
axios.get(url).then( res => {
//use res to update current state
})
}
I am getting a status 200 res from the API, but I am not getting any response data and getting an error in my console
XMLHttpRequest cannot load http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
However, if I make the request in my server.js
const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders';
axios.get(url).then(res => {
//console.log(res);
});
It works fine and I get response data when the server starts. Is this an issue with the actual API or am I doing something wrong? If this was a CORS issue I'm guessing the request in server.js wouldn't work either? Thanks!
CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Create an endpoint on your server with CORS enabled that can act as a proxy for your web app.
Fix Without Using External Proxy or Chrome Extension
CORS should be enable in server side! if you can not activate it on server (for example using external API) create a middleware React -> Middleware -> Orginal Server.
Create a Node.js project (Middleware) and use below code in app.js.
const express = require("express");
var cors = require('cors')
const app = express();
app.use(cors());
const { createProxyMiddleware } = require('http-proxy-middleware');
app.use('/api', createProxyMiddleware({
target: 'http://localhost:8080/', //original url
changeOrigin: true,
//secure: false,
onProxyRes: function (proxyRes, req, res) {
proxyRes.headers['Access-Control-Allow-Origin'] = '*';
}
}));
app.listen(5000);
This will pass the request http://localhost:5000/api/xxx to original server (for example http://localhost:8080/api/xxx), and returns the result to client.
Change client (React) to call proxy and get data without CORS error (you only need to change the port in url):
axios.get('http://localhost:5000/api/xxx', //proxy uri
{
headers: {
authorization: ' xxxxxxxxxx' ,
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
});
run node project node app.js and react project npm start.
Use the google Chrome Extension called Allow-Control-Allow-Origin: *. It modifies the CORS headers on the fly in your application.
I had the same problem. the other answers are correct but there is another solution.
you can set response header to allow cross-origin access.
according to this post you have to add the following codes before any app.get call:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
this worked for me :)
//install cors using terminal/command
$ npm install cors
//If your using express in your node server just add
var cors = require('cors');
app.use(cors())
//and re-run the server, your problem is rectified][1]][1]
**If you won't be understood then see below image**
https://i.stack.imgur.com/Qeqmc.png
I faced the same error today, using React with Typescript and a back-end using Java Spring boot, if you have a hand on your back-end you can simply add a configuration file for the CORS.
For the below example I set allowed origin to * to allow all but you can be more specific and only set url like http://localhost:3000.
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
#Configuration
public class AppCorsConfiguration {
#Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
I was having the same problem with the fetch command. A quick look at the docs from here tells us this:
If the server you are requesting from doesn't support CORS, you should get an error in the console indicating that the cross-origin request is blocked due to the CORS Access-Control-Allow-Origin header being missing.
You can use no-cors mode to request opaque resources.
fetch('https://bar.com/data.json', {
mode: 'no-cors' // 'cors' by default
})
.then(function(response) {
// Do something with response
});
You can use this code when using vs code on debugging mode.
"runtimeArgs": ["--disable-web-security","--user-data-dir=~/ChromeUserData/"]
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Chrome disable-web-security",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}",
"runtimeArgs": [
"--disable-web-security",
"--user-data-dir=~/ChromeUserData/"
]
}
]
}
Or directly run
Chrome --disable-web-security --user-data-dir=~/ChromeUserData/
Create-React-App has a simple way to deal with this problem: add a proxy field to the package.json file as shown below
"proxy": "http://localhost:8081",
I think the answer for your question is here
To have Chrome send Access-Control-Allow-Origin in the header, just alias your localhost in your /etc/hosts file to some other domain, like:
127.0.0.1 localhost yourdomain.com
Because the server don't have CORS header, so you are not allowed to get the response.
This is header from API that I captured from Chrome brower:
Age:28
Cache-Control:max-age=3600, public
Connection:keep-alive
Date:Fri, 06 Jan 2017 02:05:33 GMT
ETag:"18303ae5d3714f8f1fbcb2c8e6499190"
Server:Cowboy
Status:200 OK
Via:1.1 vegur, 1.1 e01a35c1b8f382e5c0a399f1741255fd.cloudfront.net (CloudFront)
X-Amz-Cf-Id:GH6w6y_P5ht7AqAD3SnlK39EJ0PpnignqSI3o5Fsbi9PKHEFNMA0yw==
X-Cache:Hit from cloudfront
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:b971e55f-b43d-43ce-8d4f-aa9d39830629
X-Runtime:0.014042
X-Ua-Compatible:chrome=1
X-Xss-Protection:1; mode=block
No CORS header in response headers.
I don't know if this will help but I was getting the same error when remote debugging a react-native application. I was running the debugger on 192.168.x.x:8081. I read a little bit on this Cross-Origin Resource Sharing (CORS) to educate myself on what CORS is. (I'm a beginner) and changed my URL from IP:8081 to localhost:8081 and my issue was resolved.
In my case I was getting the CORS error even after enabling it on server side. The issue was url. localhost:4001/todos I forgot to prepend the 'http'.
http://localhost:4001/todos //correct way
You don't have to deal with it on client side. Just need the following steps:
Step 1:
npm install cors
Step 2:
//express-server.js
...
const cors = require('cors');
app.use(cors());
Done!
This is a common issue occurs when you try to call an endpoint via your react app because react app is running on localhost:3000 and apis are on different servers.
to rectify this error install 'http-proxy-middleware'
npm i http-proxy-middleware
or
yarn add http-proxy-middleware
after installation create a setupProxy.js in your src folder
and follow below code
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/getDetails', //this is your api
createProxyMiddleware({
target:'http://10.0.0.20:9000/getDetails', //this is your whole endpoint link
changeOrigin: true,
})
);
app.use(
'/getproducts', //this is your api
createProxyMiddleware({
target:'http://10.0.0.20:9000/getproducts', //this is your whole endpoint link
changeOrigin: true,
})
);
};
you can add as many api as you want in app.use.
and then just normally call the api
axios.get('http://10.0.0.20:9680/getDetails')
for more details check below link
Porxying API requests in Development in React JS
Add proxy to package.json file and keep the remaining part of url in the fetch itself.
eg.,
In package.json file,
"proxy" : "https://www.google.com", //add your own website link
In App.js file
const response = await fetch(./...(as per your own))
use below after private property in package.json.
"proxy": "http://localhost:5000",
The Key is proxy and the value is your server URL
AND other thing is Chrome does not support localhost to go through the Access-Control-Allow-Origin
chrome isse cors
OR
If you use Express
please add routes after use cors
app.use(cors());
app.use('/posts', postRoutes);
add this to your server.js in your express app
const cors=require("cors");
const corsOptions ={
origin:'*',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions))
make sure to run npm install cors
I fixed the same problem by simply installing "cors" in my server folder. I used express to create an api and tried to send get request to the api but it did not work without "cors".

Categories