关于前端:node-框架-express-中使用-cors-库-配置后端跨域

44次阅读

共计 2179 个字符,预计需要花费 6 分钟才能阅读完成。

下载 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;

正文完
 0