I'm having CORS issues with a very simple app, took me about 10 minutes to code it and I've spent hours trying to fix this CORS error.
The frontend, written in React, makes a POST request to the Express backend using axios
.
app.use(cors())
is called before the single route in my Express app.
And this is the axios
request in my React app:
(await axios.post("http://localhost:3000/login", {username: username, password: password})).data.success
I'm getting this CORS error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...
Everything works fine on localhost
though.
Express code:
require('dotenv').config();
const createError = require('http-errors');
const express = require('express');
const cors = require('cors');
const compression = require('compression');
const app = express();
app.use(cors({origin: "*", allowedHeaders: ['Content-Type']}));
app.use(express.json());
app.use(compression());
app.use(express.urlencoded({extended: true}));
app.post("/login", (req, res) => {
const params = req.body;
if (params.username === process.env.USERNAME && params.password === process.env.PASSWORD)
return res.json({success: true});
else
return res.status(401).json({success: false});
});
app.use((req, res, next) => next(createError(404)));
app.listen(process.env.NODE_PORT, () => console.log("Listening on port " + process.env.NODE_PORT));
Current, not ideal, working solution:
Use the machine's IP instead of localhost
.
(await axios.post("http://192.168.*.*:3000/login", {username: username, password: password})).data.success