Express的CORS跨域设置

本文由清尘发表于2019-03-25 11:45最后修改于2019-03-31属于javascript分类

设置 Access-Control-Allow-Origin 为 * 允许所有

const express = require('express')
const booksRouter = require('./routes/booksRoute')
const app = express()
const port = process.env.PORT || 3000
const bodyParser = require('body-parser')

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials','true');
    next();
};

app.use(allowCrossDomain)
app.use(bodyParser.json())
app.use('/api',booksRouter)

app.get('/',(request,response) => {
  response.send('ok')
})

app.listen(port,() => console.log(`监听端口: ${port}`))

设置 Access-Control-Allow-Origin 为允许的域名:

var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'https://blog.ipsfan.com');
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials','true');
    next();
};