下载 cors

npm install cors

关键代码

const cors = require('cors');

app.use(cors());

app.all('*', function (req, res, next) {
  // 域名白名单, 不能写 * ,因为*是通配符 所有网站都可以访问
  // res.setHeader('Access-Control-Allow-Origin', '*');
  // 单独配置白名单,也就是能进行跨域访问的网址
  res.setHeader('Access-Control-Allow-Origin', ['http://127.0.0.1:8000']);

  //...Headers必须的固定值,"content-type"
  res.setHeader('Access-Control-Allow-Headers', 'X-request-With,content-type');
  // res.setHeader("Access-Control-Allow-Headers","X-request-With");

  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,PUT,OPTIONS');

  // 放行/下一步 不能省
  next();
});

完整代码

const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cookieSession = require('cookie-session');

const apiRoutes = require('./routes/api');

const cors = require('cors');
const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(
  cookieSession({
    name: 'session',
    secret: 'sdfasd@d34sdf@',
    maxAge: 24 * 60 * 60 * 1000 * 7,
  })
);
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));

// 相当于拼接路径
app.use('/api', apiRoutes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.all('*', function (req, res, next) {
  // 相当于域名白名单, 不能写 * ,因为*是通配符 所有网站都可以访问
  // res.setHeader('Access-Control-Allow-Origin', '*');
  // 单独配置白名单,也就是能进行跨域访问的网址
  res.setHeader('Access-Control-Allow-Origin', ['http://127.0.0.1:8000']);

  //...Headers必须的固定值,"content-type"
  res.setHeader('Access-Control-Allow-Headers', 'X-request-With,content-type');
  // res.setHeader("Access-Control-Allow-Headers","X-request-With");

  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,PUT,OPTIONS');

  // 放行/下一步 不能省
  next();
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Tom_Li
26 声望1 粉丝

热爱学习,热爱总结,热爱广博知识