My frontend :8080
and my backend :8081
are running on the same computer http://192.168.178.20
. If I navigate to http://localhost:8080
on my computer everything works fine (I can successfully send requests to my backend). When I navigate from my smartphone to http://192.168.178.20:8080
, the frontend will be displayed as intended. But I can not send requests from my smartphone to the backend, it think it has to do with the cors configuration but I could not figure it out how to change it correctly.
Do I have to whitelist my smartphone in some way on the backend? How does a proper configuration look, when I want to run this in production and not in development mode?
The smartphones private ip address (same network as computer) is 192.168.178.21
.
My current backend configuration looks like this:
import cors from 'cors';
import express from 'express';
import cookieParser from 'cookie-parser';
const SERVER_PORT = 8081;
const app = express();
app.use(cors({
origin: ['http://localhost:8080'],
credentials: true
}));
app.use(express.urlencoded({
extended: true
}));
app.use(express.json());
app.use(cookieParser());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'x-access-token, Origin, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
next();
});
// my routes ...
app.listen(SERVER_PORT, () => {
console.log(`Backend is listening on port ${SERVER_PORT}`);
});
Thanks in advance.
CodePudding user response:
From your smartphone, the origin is http://192.168.178.20:8080
, but in your CORS configuration you allow only http://localhost:8080
. Try
app.use(cors({
origin: ['http://localhost:8080', 'http://192.168.178.20:8080'],
allowedHeaders: 'x-access-token',
methods: 'GET, POST, PUT, DELETE, OPTIONS',
credentials: true
}));
and remove the (redundant) middleware that explicitly sets the Access-Control-Allow-*
headers. (Origin, Content-Type, Accept
need not be set as allowed headers, they are always allowed, unless you mean, e.g., Content-Type: application/json
.)
The IP address of the client (your smartphone) does not matter, only the address and host of the frontend server.