menu
announcement

Spectrum is now read-only. Learn more about the decision in our official announcement.

Next.js

A place to chat about Next.js and answer questions. For all other ZEIT products, check this out.

Channels
Team

CORS policy blocked

January 9, 2019 at 8:33pm
The Next.js community has a new home. This thread is preserved for historical purposes. The content of this conversation may be innaccurrate or out of date. Go to new community home →

CORS policy blocked

January 9, 2019 at 8:33pm
So a little about my setup. I basically have 2 directories. 1 is API and the other is FrontEnd (Next.js).
In FrontEnd I have ran npm run build followed by npm run start which has started my served on port 3000. My backend API is run by Laravel which i have started by running "php artisan serve". Now when I access my site through that port and perform a certain action I get the following error message:
Access to XMLHttpRequest at 'http://localhost:3000/api/auth/login/' from origin 'http://mydomain.com:3000' 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.
Here is my server.js script:
const express = require('express');
const next = require('next');
const bodyParser = require('body-parser');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const devProxy = {
'/api': {
pathRewrite: {'^/api': '/'},
changeOrigin: true
}
};
app.prepare().then(() => {
const server = express();
// Set up the proxy.
if (dev && devProxy) {
const proxyMiddleware = require('http-proxy-middleware');
Object.keys(devProxy).forEach(function (context) {
server.use(proxyMiddleware(context, devProxy[context]))
})
}
server.use(bodyParser.json()); // support json encoded bodies
server.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
server.get('/profile/:username', (req, res) => {
const actualPage = '/profile';
return app.render(req, res, actualPage);
});
server.get('/profile/:username/:page', (req, res) => {
let actualPage = '/profile';
if (req.params.page === 'profilesettings') {
actualPage = '/profilesettings';
}
return app.render(req, res, actualPage);
});
server.get('/project/:projectId/edit', (req, res) => {
const actualPage = '/projectedit';
return app.render(req, res, actualPage);
});
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
Can anyone help me figure out what to do here to get it working and connecting with my backend that is on port 8000 (laravel)?

January 9, 2019 at 8:53pm
This errors indicates that the server you are accessing need to add cors headers. Search cors. It is general issue
Thing is I have tried to add the following to my server.js but still get the same issue
server.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();
});
Check the network tab
I read that there are issues with localhost with this regard
that is where I saw that error message, in my chrome network tab
No, the response headers in the network tab, see what you r actually receving
Error occured while trying to proxy to: localhost:3000//auth/login/
Not sure why there are 2 /
because when I run npm run dev (babel-node server.js --presets /env) everything is fine
this is exactly whats in the network tab:
commons.916395b80e13e35ea0d0.js:17 OPTIONS http://localhost:3000/api/auth/login/ 504 (Gateway Timeout)
(anonymous) @ commons.916395b80e13e35ea0d0.js:17
e.exports @ commons.916395b80e13e35ea0d0.js:17
e.exports @ commons.916395b80e13e35ea0d0.js:42
Promise.then (async)
l.request @ commons.916395b80e13e35ea0d0.js:42
(anonymous) @ commons.916395b80e13e35ea0d0.js:17
t.a @ commons.916395b80e13e35ea0d0.js:12
(anonymous) @ commons.916395b80e13e35ea0d0.js:12
e.exports @ commons.916395b80e13e35ea0d0.js:12
e.exports @ commons.916395b80e13e35ea0d0.js:48
e.exports @ commons.916395b80e13e35ea0d0.js:12
(anonymous) @ commons.916395b80e13e35ea0d0.js:17
(anonymous) @ commons.916395b80e13e35ea0d0.js:59
(anonymous) @ commons.916395b80e13e35ea0d0.js:33
p @ commons.916395b80e13e35ea0d0.js:33
(anonymous) @ commons.916395b80e13e35ea0d0.js:33
E @ commons.916395b80e13e35ea0d0.js:33
S @ commons.916395b80e13e35ea0d0.js:33
k @ commons.916395b80e13e35ea0d0.js:33
N @ commons.916395b80e13e35ea0d0.js:33
jn @ commons.916395b80e13e35ea0d0.js:33
Fi @ commons.916395b80e13e35ea0d0.js:33
Le @ commons.916395b80e13e35ea0d0.js:33
Sn @ commons.916395b80e13e35ea0d0.js:33
Ri @ commons.916395b80e13e35ea0d0.js:33
_n @ commons.916395b80e13e35ea0d0.js:33
:3000/#:1 Access to XMLHttpRequest at 'http://localhost:3000/api/auth/login/' from origin 'http://mydomain.com:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
This is console . Devtoools -> application -> network. Then clear. Do the fetch. Choose the relevant line and see list of actual headers

January 10, 2019 at 8:49am
Is the middleware that you have written to add the headers included before your route definitions/handlers? If it is after them then the requests will be processed first.
check your nginx config

January 10, 2019 at 6:25pm
currently no nginx involved
this is how it is written (if thats what you mean):
const express = require('express');
const next = require('next');
const bodyParser = require('body-parser');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const devProxy = {
'/api': {
target: 'http://localhost:8000/api',
pathRewrite: {'^/api': '/'},
changeOrigin: true
}
};
app.prepare().then(() => {
const server = express();
server.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();
});
// Set up the proxy.
if (dev && devProxy) {
const proxyMiddleware = require('http-proxy-middleware');
Object.keys(devProxy).forEach(function (context) {
server.use(proxyMiddleware(context, devProxy[context]))
})
}
server.use(bodyParser.json()); // support json encoded bodies
server.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
server.get('/profile/:username', (req, res) => {
const actualPage = '/profile';
return app.render(req, res, actualPage);
});
server.get('/profile/:username/:page', (req, res) => {
let actualPage = '/profile';
if (req.params.page === 'profilesettings') {
actualPage = '/profilesettings';
}
return app.render(req, res, actualPage);
});
server.get('/project/:projectId/edit', (req, res) => {
const actualPage = '/projectedit';
return app.render(req, res, actualPage);
});
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
the header stuff is right after defining express()
ok fixed the cors issue by removing the if statement around the proxyMiddleware stuff
but now I have this:
OPTIONS http://localhost:3000/api/auth/login/ net::ERR_CONNECTION_REFUSED
dispatchXhrRequest @ xhr.js:175
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
in chrome console tab
i i see because of this:
Data: { message: 'could not find driver (SQL: select * from "projects" order by "created_at" desc)',
exception: 'Illuminate\\Database\\QueryException',
file: '/root/maketube/api/vendor/laravel/framework/src/Illuminate/Database/Con nection.php',
line: 664,
Show more messages