我一直得到这个错误
被CORS策略阻止:请求的资源上没有“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”,以便在禁用CORS的情况下获取资源。
这是我的特快密码
null
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}!`))
null
尝试cors
中间件包在express App中启用内核。
作为生产依赖项安装。
npm install --save cors
示例:
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}!`))