So I'm working in React and keep getting different cors errors. On the internet I found that you can use express to solve the problem!
But now I keep getting the following error:
TypeError: Cannot read property 'prototype' of undefined
I tried 2 different solutions but it just doesn't work:
var express = require('express')
var cors = require('cors')
var app = express()
app.options('*', cors())
export const fetchData = (url, key) => {
let myHeaders = new Headers();
myHeaders.append("Authorization", 'Bearer ' + key);
let requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow',
};
return fetch(url, requestOptions)
.then(response => response.json())
.then(result => result)
.catch(error => console.log('error', error))
}
The other one I tried is
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
Can someone tell me what I'm doing wrong ?
Try to do both of this:
app.use(cors());
app.options('*', cors());
This resolved all my problems with CORS.
use this code to solve cors error
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,X-Access-Token,XKey,Authorization');
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', 0);
next();
});
Related
I'm doing a backend in express, and frontend with react. And tried to send this cookie with a small expiration time, it has the configuration of cors working (for get, post, etc methods), and the fetch in react with axios and fetch (I have tried both)
The thing is, this code worked in Insomia and also in the URL of the server in the browser, but not in React. Why is that?
code:
`
const app = express()
headersConfiguration()
import cookieParser from 'cookie-parser';
const info = {
name: 'marcos',
apellidos: 'woodward'
}
// config basica:
app.use(cors());
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cookieParser("secretKey"))
app.get("/cookies", (req, res) => {
// const data = req.body
res.cookie(`primeraPrueba`, info.name, { maxAge: 600000 }).send(`cookie ready!`)
})
`
headers:
`
import express from "express";
const server = express();
export default function headersConfiguration() {
server.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000/'); // update to match the domain you will make the request from
res.header('Access-Control-Allow-Credentials', 'false');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
next();
});
}
`
frontend (react):
this works with a button to make it simple:
`
const cookies = (e) => {
e.preventDefault()
axios.get("http://localhost:8080/cookies")
.then(function (response) {
document.cookies = response
console.log(response.cookie)
})
// fetch("http://localhost:8080/cookies")
}
`
I tried fetch, axios, changing the express headers between * and the specific url. also document.cookies = response.data in the front.I need q to save the cookie respecting the expiration.
I have a React app (localhost:3000) and a Node app (localhost:3001) to run a simple system. The problem is I'm getting the error Access to XMLHttpRequest at 'localhost:3001/app' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
I have tried with app.use(cors()) and also with cors options as below. Still I'm getting the above error.
Node app.js
const express = require('express');
const app = express();
const cors = require('cors');
const corsOptions = {
origin: 'http://localhost:3000/',
credentials: true,
optionSuccessStatus: 200
}
app.use(cors(corsOptions));
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', "http://localhost:3000");
res.header('Access-Control-Allow-Headers', true);
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
next();
});
app.use(express.json());
app.get('/app', (req, res) => {
res.send({result: "hello"});
});
module.exports = app;
React app.js
import React, { Component } from "react";
import axios from 'axios';
class App extends Component {
componentDidMount(){ this.runInstance(); }
runInstance = () => {
axios.get(`localhost:3001/app`)
.then(res => {
console.log("res", res);
})
.catch(err => {
console.log("AXIOS ERROR:", err);
})
}
render() { return(<div></div>) }
}
export default App;
How can I solve this?
Since you use nodejs
installing cors
npm install cors
After that
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
Then after applying "cors" middleware. You need to insert "http://" before "localhost: in your react app".
Example
axios.get(`http://localhost:3001/api/app`)
.then(res => {
console.log("res", res);
})
.catch(err => {
console.log("AXIOS ERROR:", err);
})
You are using a different port to the one defined in corsOptions, try like below.
// app.js
...
runInstance = () => {
axios.get(`http://localhost:3000/app`)
.then(res => {
console.log("res", res);
})
.catch(err => {
console.log("AXIOS ERROR:", err);
})
}
...
Update:
Change all references to 3000 to be 3001, so that your CORS configuration matches the request you are trying to make.
const corsOptions = {
origin: 'http://localhost:3001/',
credentials: true,
optionSuccessStatus: 200
}
...
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', "http://localhost:3001");
...
});
I simply want to POST data from a js-script to a node-server application which i run with express.
When sending the data i get: CORS-Header 'Access-Control-Allow-Origin' does not match with 'localhost:3000'.
Client-Script:
let url = 'http://localhost:3000/api'
const options = {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: jsonData,
};
fetch(url, options)
Server-Script:
const express = require('express');
const app = express()
app.listen(3000, () => console.log('Listening at 3000'))
app.use(express.static(__dirname))
const cors = require("cors")
app.use(cors({ origin: 'localhost:3000' }));
app.post('/api', (request, response) => {
console.log(request)
})
If i open the network-analyzer from Firefox, this is what i get:
fetch
How can i solve this issue?!
Thanks a Lot,
Max
Use this extension for local development
Allow CORS: Access-Control-Allow-Origin
If you add:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
it works just fine!
src: https://dzone.com/articles/cors-in-node
I think app.use(cors({ origin: 'localhost:3000' })); should be app.use(cors({ origin: 'http://localhost:3000' }));
https://github.com/expressjs/cors#configuring-cors
I keep getting the "No 'Access-Control-Allow-Origin' header is present on the requested resource" error even though I have the following middleware in my express server (which is placed before all other middleware):
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 5000;
const cors = require("cors");
const workoutRoutes = require("./routes/workoutRoutes");
const exerciseRoutes = require("./routes/exerciseRoutes");
const userRoutes = require("./routes/userRoutes");
const checkAuth = require("./middleware/check-auth");
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type, Authorization"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
app.use("/users", userRoutes);
app.use(checkAuth);
app.use("/workouts", workoutRoutes);
app.use("/exercises", exerciseRoutes);
app.listen(PORT);
I know this question has been asked multiple times, but none of the solutions have worked for me, including using the cors npm package.
This is the alternative middleware that I tried using the cors module, which produces the same error:
app.options("*", cors());
app.use(cors({ origin: null }));
Any advice into why I could still be getting this error would be greatly appreciated. Thank you.
I figured out the issue, I was making the requests without a valid token, causing the following checkAuth middleware to respond with 'No valid token'.
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization;
if (!token) {
res.send("No valid token");
}
next();
} catch (error) {
console.log(error);
return;
}
};
What I still don't understand is why this response did not have the appropriate headers attached if the checkAuth middleware is run after the cors middleware. Anyway, thank you all for your help.
I have used Postman to send Post requests and they are working fine but when I try to use axios it is giving me this error.
createAnimeList.js:27
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 POST http://localhost:4000/animes/add
net::ERR_CONNECTION_REFUSED
This is my backend code
router.post("/add", async (req, res) => {
console.log("Heeeere");
console.log(req.body.animeName);
var anime = new Animes({
animeName: req.body.animeName,
});
anime = await anime.save();
return res.send(anime);
});
Here is my React code where I am using Axios
onSubmit(event) {
event.preventDefault();
const anime = {
animeName: this.state.animeName,
};
console.log(anime);
axios
.post("http://localhost:4000/animes/add", anime)
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
//window.location = "/anime";
}
Seems like a CORS issue
Install that on your node server:
https://www.npmjs.com/package/cors
Here is a simple example of node server with CORS enabled using this lib.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port
80')
})
you need to enable CORS( Cross-Origin-Resoruce-Sharing)
you can either use the cors package
https://www.npmjs.com/package/cors
or this code
place this controller before every controller in your application
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // to enable calls from every domain
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE'); // allowed actiosn
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200); // to deal with chrome sending an extra options request
}
next(); // call next middlewer in line
});
It's a CORS issue:
You need to add the follow code in your backend:
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors({
credentials:true,
origin: ['http://localhost:PORT']
}));
Inside origin array you need to insert those urls who are in the white list.