I defined my Express js app:
const express = require('express') var history = require('connect-history-api-fallback'); const path = require('path') const http = require('http') const socketio = require('socket.io') require('./db/mongoose') const userRouter = require('./routers/user') const publicDirPath = path.join(__dirname, '../public') const app = express() app.use(express.static(publicDirPath)) app.use(history({ index: '../public/index.html' })) app.use(express.static(publicDirPath)) app.use(express.json()) app.use(userRouter) const server = http.createServer(app) const io = socketio(server) io.on('connection', socket => { console.log('New WebSocket connection') socket.on('join', () => { socket.emit('message', 'Welcome to the app') }) }) module.exports = server Then I use it my index.js file:
const app = require('./app') const port = process.env.PORT app.listen(port, () => { console.log(`Server is up on port ${port}`) }) When I run the app and send requests from the same port - everything works just fine. But when I try to send requests from different localhost port, ie. 8080, I'm getting cross origin error. I tried to install cors package and use it as follows:
const cors = require('cors') app.options('*', cors()) app.use(cors()); And got the same result.
I tried to pass configuration to cors:
app.use(cors({ origin: 'http://localhost:8080' })); And still got the same result.
What am I doing wrong and how can I make it work?
cors()(and is different from what you're showing you tried).process.env.PORT, obviously no other ports would work.Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5555/users/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).localhost:5555 is where my express server runs.