How can i resolve the No 'Access-Control-Allow-Origin' problem? - node.js

I am using Heroku to run my server, and I am using 'cores' at my backend side that wrote in Node.js.
I have these commands:
const corsConfig = {
origin: true,
credentials: true
};
app.use(cors(corsConfig));
app.options("*", cors(corsConfig));
in my client i am using vue.js:
module.exports = {
devServer: {
proxy: {
'/api': {
target: '"https://david-matan-recipe-api-server.herokuapp.com/',
ws: true,
changeOrigin: true
}
}
}
}
when I am trying to get some data from my backend with Axios I get this message at my browser:
Access to XMLHttpRequest at 'https://david-matan-recipe-api-server.herokuapp.com/api/recipes/random' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

try to set config like this:
const corsConfig = {
origin: 'http://localhost:8080'
};

Related

Why Axios request to a node(Express) back-end api still preflight OPTIONS request even if http-proxy-middleware is configured?

I'm trying to figure out why when I make a call to my "API" (nodejs express) from my React client the OPTIONS, preflight request is executed first.
Server api run on http://localhost:8000
Client run on http://localhost:3000
In my React client I configured http-proxy-middleware as follows:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
Also the Axios instance is created with following options
const options = {
baseURL: BASE_URL,
timeout: 300000,
withCredentials: false,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}
};
axios.create(config);
The Node.js(Express) BackEnd application is configured as follow:
app.use(cors(
{
"origin": "*", // just for test...
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"allowedHeaders": "*" // just for test
}
));
When I make a Post for instance for server-side token validation a preflight OPTIONS request is made. How can I avoid this ? Am I doing something wrong?
Thank you all.

The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute wont work

I am having this problem when trying to use withCredentials that it tells me that I need
Access to XMLHttpRequest at 'http://localhost:3005/api/v1/user' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
async function getUser() {
const user = await axios.get("http://localhost:3005/api/v1/user", {
withCredentials: true, headers: {
'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}
});
console.log(user)
}
useEffect(() => {
getUser();
}, [])
Researching this people are telling me that I need to activate cors on the server. But from what I can tell I have already done that by doing this + npm I cors.
const cors = require('cors')
var app = express();
const corsOptions ={
origin:'*',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions))
If I remove the withCredentials everything works fine the problem is that I need the connect.sid cookie on the server in order to log in the user.
I have had this problem before. Solved it by changing the * to ['http://localhost:3000']
So your code should say:
const cors = require('cors')
var app = express();
const corsOptions ={
origin:['http://localhost:3000'],
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions))

Socket io v3 connection has been blocked by CORS policy

I have cors error while using Socketio v3
the app is on React backed by Nodejs
Server Side Codes:
var server = http.createServer(app);
var port = process.env.PORT || '3000'
const io = require("socket.io")(server,{
cors: {
origin: "*:*",
methods: ["PUT", "GET", "POST", "DELETE", "OPTIONS"],
allowedHeaders:["secretHeader"],
credentials: true
}
})
Client Side Connecting code:
const SOCKET_URL = "https://fakeurl.org";
socket.current = io(`${SOCKET_URL}`,{
secretHeader:{
"Access-Control-Allow-Headers": "*"
}
});
And i got the following error:
Access to XMLHttpRequest at
'https://fakeurl.org/socket.io/?EIO=4&transport=polling&t=NOdqBkN'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Refer to Socket.io Handling CORS.
// server-side
const io = require("socket.io")(server,{
cors: {
origin: "*",
methods: ["PUT", "GET", "POST", "DELETE", "OPTIONS"],
allowedHeaders:["secretHeader"],
credentials: true
}
})
// client-side
const SOCKET_URL = "https://fakeurl.org";
socket.current = io(`${SOCKET_URL}`,{
withCredentials: true,
extraHeaders: {
"secretHeader": "secret value"
}
});

CORS error even with cors nom package installed

I am using React Filepond and the uploading part is working fine. But when I go to an existing record and try to display the image, I get a CORS error:
Access to XMLHttpRequest at 'http://localhost:8000/img/myImg.jpg'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
in app.js on my node server I have the below but I still get the cors error using the cors package
const cors = require("cors");
app.use(cors());
app.options("*", cors());
In React I have the following:
state = {
data: {
title: "",
bgImg: ""
},
errors: {},
files: [
{
source: "myImg.jpg",
options: {
type: "local"
}
}
]
};
<FilePond
ref={ref => (this.pond = ref)}
files={this.state.files}
allowMultiple={false}
maxFiles={1}
name="bgImg"
server={{
process: "http://localhost:8000/api/uploads/",
load: "http://localhost:8000/img/"
}}
oninit={() => this.handleInit()}
onupdatefiles={fileItems => {
this.setState({
files: fileItems.map(fileItem => fileItem.file)
});
}}
/>
In package.json I have also added a proxy:
"proxy": "http://localhost:8000/img",
Network tab -> headers tab shows
Request URL: http://localhost:8000/img/myImg.jpg
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Referer: http://localhost:3000/home-banner
Try installing cors plugin in your browser and access the api. Hope this helps..
const cors = require('cors')
const corsOptions = {
origin: 'http://localhost:8000'
}
app.get('/img', cors(corsOptions), (req, res, next) => {
//...
})

How to fix "Response to preflight request doesn't pass access control check: It does not have HTTP ok status" error in react app with nodejs api

I have been trying to do an api call (nodejs with express running on localhost) from a react app running in the browser over a local dev server (web-pack dev server). Everything was working well until I tried to call the api. They are both running on separate ports.
I have tried adding the cors headers (Recommended by MDN) to both the post call (from the app in browser) and to the response from the Nodejs API but neither of these solved the issue.
Code for the api call (in browser):
const headers = {
'Content-Type': 'application/json',
'access-token': '',
'Access-Control-Allow-Origin': '*',
}
export default async () => {
try {
const body = JSON.stringify({
test: true,
})
const response = await fetch('http://localhost:1337/internal/provider/check_email_exist', {
method: 'POST',
headers,
body,
})
console.log(response)
} catch (e) {
return e
}
}
API Middleware (in nodejs):
// Verify All Requests
app.use(VerifyToken)
// Compress
app.use(compression())
// Helmet middlware
app.use(helmet())
// Body Parser
app.use(bodyParser.urlencoded({
extended: false,
}))
app.use(bodyParser.json())
The expected result is to just give a 200 status code and respond with the data.
The actual output is:
OPTIONS http://localhost:1337/internal/provider/check_email_exist 404 (Not Found)
Access to fetch at 'http://localhost:1337/internal/provider/check_email_exist' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Since you're using webpack-dev-server you can use the proxy option DevServerProxy.
Your configuration will look like this:
// webpack.config.js
devServer: {
proxy: {
'/internal': 'http://localhost:1337'
}
}
Since I can't see your express routes on your question I'm speculating about the proxy route if your API lives on /internal endpoint then you should modify your React code like this:
const response = await fetch('/internal/provider/check_email_exist', {
method: 'POST',
headers,
body,
})
As you can see I ommited the https://localhost:1337 because the proxy option from webpack-dev-server will handle this and it will redirect to http://localhost:1337. Hope this will help you. Cheers, sigfried.
EDIT
As the comment on your question pointed out you should set the headers on your express server, not the client, for this task you can use the cors-middleware package.
Maybe this can help if you face with preflight errors.
My full config:
const cors = require('cors');
const express = require('express');
const { createProxyMiddleware: proxy } = require('http-proxy-middleware');
...
const logLevel = 'info';
const ip = require('ip').address();
const proxyOptions = {
xfwd: true,
target,
changeOrigin: true,
logLevel,
cookieDomainRewrite: {
'*': 'localhost',
},
headers: {
'X-Forwarded-For': ip,
'X-Node': 'true',
},
};
const backNginxApp = express();
backNginxApp.use(
cors({
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
origin: 'http://localhost:3000',
optionsSuccessStatus: 200,
credentials: true,
})
);
backNginxApp.use('/api', proxy(proxyOptions));
API: const target = 'https://someapi.com'
Local development running at: http://localhost:3000

Resources