设置Express
const express = require('express')
const bodyParser = require('body-parser')const app = express()
// 处理参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));// 设置允许跨域访问该服务
app.all('*', function (req, res, next) {res.header("Access-Control-Allow-Origin", "*");res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');res.header("Access-Control-Allow-Headers", "X-Requested-With");res.header('Access-Control-Allow-Headers', 'Content-Type');next();
});// 启动监听
app.listen(3000, () => {console.log('running...')
})
因为一直报错(Access to fetch at ‘http://localhost:3000/books’ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.)。
所以在网上找了这段代码,能够成功执行:
//设置跨域请求
app.all('*', function (req, res, next) {//设置请求头//允许所有来源访问res.header('Access-Control-Allow-Origin', '*')//用于判断request来自ajax还是传统请求res.header("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");//允许访问的方式res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')//修改程序信息与版本res.header('X-Powered-By', ' 3.2.1')//内容类型:如果是post请求必须指定这个属性res.header('Content-Type', 'application/json;charset=utf-8')next()
})
使用NPM包
或者也可以直接使用别人写好的npm包,更加方便简单:
下载:
npm install cors
使用:
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())