使用devServer解决跨域问题

目前解决跨域主要的方案有:

jsonp(淘汰)
cors
http proxy
此处介绍的使用devServer解决跨域,其实原理就是http proxy

将所有ajax请求发送给devServer服务器,再由devServer服务器做一次转发,发送给数据接口服务器

由于ajax请求是发送给devServer服务器的,所以不存在跨域,而devServer由于是用node平台发送的http请求,自然也不涉及到跨域问题,可以完美解决!

服务器代码(返回一段字符串即可):

const express = require('express')
const app = express()
// const cors = require('cors')
// app.use(cors())
app.get('/api/getUserInfo', (req, res) => {
  res.send({
    name: '黑马儿',
    age: 13
  })
});

app.listen(9999, () => {
  console.log('http://localhost:9999!');
});

前端需要配置devServer的proxy功能,在webpack.dev.js中进行配置:

devServer: {
    open: true,
    hot: true,
    compress: true,
    port: 3000,
    // contentBase: './src'
    proxy: {
      '/api': 'http://localhost:9999'
    }
  },

意为前端请求/api的url时,webpack-dev-server会将请求转发给http://localhost:9999/api处,此时如果请求地址为http://localhost:9999/api/getUserInfo,只需要直接写/api/getUserInfo即可,代码如下:

axios.get('/api/getUserInfo').then(result => console.log(result))

 

posted @ 2020-04-22 23:03  午亭爱成长  阅读(4553)  评论(0编辑  收藏  举报