------by 19201314
express中的代码: 我是直接从下面这个index.js启动,并没有从www.js启动,所以配置跨域时跟app.js没有关系。
index.js
const express = require('express')
const mongoose = require('mongoose')
const Book = require('./model/Book')
const app = express()
mongoose.connect('mongodb://127.0.0.1:27017/bookstore')
app.get("/books",(req,res)=>{
Book.find()
.then((books)=>{
res.send(books)
})
})
app.listen(3000)
vue-cli中axios所以
this.axios({
method :'get',
url:'你请求的localhost或者其它',
data: {
},
}).then((res)=>{
}).catch(err => {
})
通过其它博客发现Access-Control-Allow-Headers 是X-Requested-With,所以试了很多次依然跨域失败,经过查看请求头发现并不是,将X-Requested-With改为content-type
所以配置跨域,直接在index.js中app.get()之前插入
app.all('*', (req, res, next) => {
console.log("aa")
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "content-type"); //注意
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", 'Express');
res.header("Content-Type", "application/json;charset=utf-8");
console.log("qq")
next();
})