关于express和vue cli跨域问题

------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();
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值