首页 > 其他 > 详细

使用devServer解决跨域问题

时间:2020-04-23 00:57:19      阅读:151      评论:0      收藏:0      [点我收藏+]

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

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))

 

使用devServer解决跨域问题

原文:https://www.cnblogs.com/wtsx-2019/p/12757595.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!