I want to fetch my NodeJS server, but I receive a Cross-Origin Request echec.
This is my index.js server :
const express = require('express')
if (process.env.NODE_ENV !== 'production') require('dotenv').config()
const routerIdeas = require('./routes/ideas')
const PORT = process.env.PORT || 5000
const app = express()
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")
res.send(200)
next()
})
app.use('/api', routerIdeas)
app.listen(PORT, () => {
console.log(`Server is running on port : ${PORT}`)
})
I also tried with the npm CORS package but it's the same problem :
const express = require('express')
var cors = require('cors')
if (process.env.NODE_ENV !== 'production') require('dotenv').config()
const routerIdeas = require('./routes/ideas')
const PORT = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use('/api', routerIdeas)
app.listen(PORT, () => {
console.log(`Server is running on port : ${PORT}`)
})
And this is my fetch by the React app :
useEffect(() => {
const getIdeas = async () => {
setIsLoading(true)
try {
const response = await fetch("https://localhost:3004/api/ideas")
const data = await response.json()
setIdeasArray(data)
setIsLoading(false)
} catch (err) {
console.error('getIdeas error: ', err, err.stack)
}
}
getIdeas()
}, [])
The browser's console always answer :
Blocking a Cross-Origin Request: the "Same Origin" policy does not allow viewing of the remote resource located at https://localhost:3004/api/ideas. Reason: CORS request failed.
Sorry, it was just a stupid error :
Wrong fetch URL => https://localhost:3004/api/ideas
Good fetch URL => http://localhost:3004/api/ideas
Why don't you use CORS node package (link)
Related
While trying to carry out put axios request the following error occurs:
The CORS module was installed and switched in server.js file, but seems that doesn't work.
By the way there are no any CORS headers in the request:
So in server.js file the CORS module is implemented. I tried to add {origin: "http://localhost:3000"} in brackets but that didn't work. The brackets are empty.
server.js:
const express = require("express");
const mongoose = require("mongoose");
const apiRoutes = require('./routes/apiRoutes');
const path = require('path');
const cors = require("cors")
require("dotenv").config();
const app = express();
const PORT = 3001;
app.use(cors());
app.use(express.static(path.join(__dirname, 'images')));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(apiRoutes);
mongoose
.connect(process.env.MONGO_URL)
.then(res => console.log("The connection to the Database was carried out successfully."))
.catch(error => console.log(`The Error while connecting to the Database occured: ${error.message}`))
app.listen(PORT, 'localhost', error =>
console.log(error ? `The Error occured: ${error.message}.` : `The Listening Port is ${PORT}`)
);
the route:
router.put("/api/newAd/:creationDate", (req, res) => {
console.log(req.body);
// Ad.updateOne({ creationDate: req.body.creationDate }, {
// textInfo: req.body
// })
})
the client side:
const saveAndPlace = () => {
axios.put(`/api/newAd/${creationDate}`)
.catch(err => console.log("error", err))
};
So why these errors occur? And why the headers are not shown in the network panel?
The error message says nothing about CORS. The URL and the Referer have the same origin so it isn't even a cross-origin request!
What it does says is "Blocked by Client" on a URL with "Ad" in it which strongly suggests that the problem is an ad-blocking extension extension installed in the browser.
I have deployed my blog app on heroku, I started with 2 folders api and client after that I put my client folder in api folder and delpoyed on heroku.
I am getting an error from cors despite all efforts.
Can you let me know what am i doing wrong
Access to XMLHttpRequest at 'https://blogapi556.herokuapp.com/api/posts' from origin 'https://blogapp556.herokuapp.com' 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.
Server Js looks like this.
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const userRoute = require("./routes/users");
const postRoute = require("./routes/posts");
const categoryRoute = require("./routes/categories");
const multer = require("multer");
const path = require("path");
let port = process.env.PORT || 5000;
dotenv.config();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
app.use(express.json());
app.use("/images", express.static(path.join(__dirname, "/images")));
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(console.log("Connected to MongoDB"))
.catch((err) => console.log(err));
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(null, req.body.name);
},
});
const upload = multer({ storage: storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
res.status(200).json("File has been uploaded");
});
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);
app.use("/api/categories", categoryRoute);
app.use(express.static(path.join(__dirname, "/client/build")));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/client/build', 'index.html'));
});
app.listen(port, () => {
console.log("Backend is running.");
});
The request in client looks like this
const fetchPosts = async () =>{
const res = await axiosInstance.get("/posts" + search);
console.log(res);
setPosts(res.data)
}
Axios Config File like this
import axios from "axios"
const axiosInstance = axios.create({
baseURL: "https://blogapi556.herokuapp.com/api/",
})
axiosInstance.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
export {axiosInstance}
You need to install the CORs NPM package.
Using
$ npm i cors
Require this in your server.js file.
const cors = require('cors')
For simple usage to enable all CORs you can simply add this to your server.js file.
app.use(cors())
Check out the Express docs for CORs here
I am developing the admin interface for my software and it was working fine in development (when I 'react start'). The problem is when I build and run it in production. React-admin won't load the data coming from the server, because of these 2 error in its requests.
OPTIONS http://localhost:3000/user?filter={}&range=[0,9]&sort=["id","ASC"] - CORS FAILED
GET http://localhost:3000/user?filter={}&range=[0,9]&sort=["id","ASC"] - NS_ERROR_DOM_BAD_URI
in development react-admin doesn't request 'options /user' neither I get these errors. I am using node express in the server side:
require('dotenv').config();
const express = require('express')
var cors = require('cors')
const app = express()
const port = process.env.SERVER_PORT;
const serverIp = process.env.SERVER_IP;
const { verifyUser } = require('./middleware/verification');
const { readUsers } = require('./db/dbManager');
app.use(cors())
app.get('/user', verifyAdmin, (req, res) => {
readUsers().then((response) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
res.setHeader('Content-Range', 'posts 0-24/319');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response));
});
})
app.options('/user', verifyAdmin, (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
res.setHeader('Content-Range', 'posts 0-24/319');
res.setHeader('Content-Type', 'application/json');
res.end();
})
app.use(express.static('build'));
app.listen(port, () => {
console.log(`Example app listening at http://${serverIp}:${port}`)
});
How can I fix these errors I am having in production?
I was searching for a similiar issue, but I still can't fix this problem. I'm working on a chat app in ReactJs, Node/Express, Mongoose and Socket.io. Everything works, db is working, server is running, so now I want to add socket. I'm trying to connect client side with server, but I get error (about every 2/3sec) POST/GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=N5PeKkf 404 (Not Found).
React:
const host = 'http:localhost:5000/api/rooms'
const [endpoint, setEndpoint] = useState('')
const {width,mobileWidth} = props;
useEffect(()=>{
setEndpoint(`${host}${props.location.pathname}`);
socket = io(endpoint);
const roomId = props.location.pathname.slice(1,props.location.pathname.length);
socket.emit('join', {roomId})
},[endpoint])
Node:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const socketIo = require("socket.io");
const http = require("http");
const HttpError = require('./models/http-error');
const roomsRouter = require('./routes/rooms-routes');
const usersRouter = require('./routes/users-routes');
const app = express();
mongoose
.connect(
`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#cluster0-lnoai.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
)
.then(() => {
app.listen(process.env.PORT || 5000);
})
.catch(err => {
console.log(err);
});
const server = http.createServer(app);
const io = socketIo(server);
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
next();
});
io.on('connection',(socket)=>{
console.log('connected');
})
app.use('/api/rooms', roomsRouter);
app.use('/api/users', usersRouter);
app.use((req, res, next) => {
throw new HttpError('Route not found.', 404);
});
app.use((error, req, res, next) => {
if (res.headerSent) {
return next(error);
}
res.status(error.code || 500).json({
message: error.message || 'An uknown error occurres!',
errorCode: error.code || 500
});
});
I am trying to make API calls using express js to get some data and then use them for my school project!
I have heard that I can install an extension or something like that on my browser but that will only work on my pc.
So I am trying to create my own proxy using Express JS.
Do I need to write something else on I app.get('/') or is it okay with a slash.
Thanks in advance!
const express = require('express');
const request = require('request');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
let key1 = '8151a53b2c1d4c3db2df'
let url ='http://api.sl.se/api2/realtimedeparturesv4.json?key='+key1+'&siteid=9192&timewindow=5'
app.get('/', (req, res) => {
request( { url: url},
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', message: err.message });
}
res.json(JSON.parse(body));
console.log(body);
} )
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));```
Use the cors package like this
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
if you want to enable it for a single route :
app.get('/', cors(), (req, res) => {
});