Reputation: 123
I keep getting this error
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is my Express code
const express = require('express')
const app = express()
const port = 3001
var redis = require("redis"),
client = redis.createClient();
const {promisify} = require('util')
const getAsync = promisify(client.get).bind(client);
app.get('/jobs', async (req, res) => {
const jobs = await getAsync('github');
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return res.send(jobs);
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Upvotes: 0
Views: 523
Reputation: 10569
Try the cors
middleware package to enable cores in express app.
install as a production dependency.
npm install --save cors
Example:
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3001
var redis = require("redis"),
client = redis.createClient();
const { promisify } = require('util')
const getAsync = promisify(client.get).bind(client);
const allowedOrigins = ["http://localhost:3000"];
app.use(cors({
origin: function (origin, callback) {
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));
app.get('/jobs', async (req, res) => {
const jobs = await getAsync('github');
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return res.send(jobs);
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Upvotes: 1