vue和react中的跨域解决

开发环境下跨域如何解决:

https://blog.csdn.net/weixin_39553363/article/details/104152142?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-7.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-7.control

vue.config.js是总个webpack的配置表,它会把里面的配置传送给node服务器,在vue根目录下新建一个vue.config.js文件,当我们服务启动的时候,这个配置表会注册到webpack里面去的。webpack里面有node.js的中间件,因此会被注册到里面去,从而启动我们node.js里面的服务。
module.exports = {
	  devServer:{                //记住,别写错了devServer
	    host:'localhost',        //设置本地服务器   选填
	    port:8080,				//设置本地默认端口  选填
	    proxy:{                 //设置代理,必须填
	      '/api':{              //设置拦截器  拦截器格式   斜杠+拦截器名字,名字可以自己定
	        target:'http://t.yushu.im',     //代理的目标地址,这是豆瓣接口地址网址
	        changeOrigin:true,              //是否设置同源,输入是的
	        pathRewrite:{                   //路径重写
	          '/api':''                     //选择忽略拦截器里面的单词
	        }
	      }
	    }
	  }
}

注意:代理原理

我们想要访问的目标接口地址是 http://t.yushu.im/v2/movie/in_theaters
现在,我们把这串地址的 http://t.yushu.im 这部分用拦截器 /api 替代,也就是说,当服务器启动的时候,在文件中读取到 ‘ /api ’ 这串字符串的时候,会变成 http:localhost/8080/api/v2/movie/in_theaters,而此时路径重写设置为忽略拦截器的名字,也就是说不包含拦截器的名字,因此,访问路径会变成这样,是这样 http:localhost/8080/v2/movie/in_theaters,最后,路径就成功伪装成与豆瓣网的亲戚啦,顺利闯过了浏览器的关卡啦,就可以正常获取到数据啦。

详细代码:

baseURL: ‘/api’ // 基础路径
这是封装好的基础路径
/**
 * 封装 axios 请求模块
 */
import axios from 'axios'
// Vue.prototype.$axios = Axios
// Axios.defaults.baseURL = '/api'
import store from '@/store/index.js'

const request = axios.create({
  baseURL: '/api' // 基础路径
})
// 请求拦截器
request.interceptors.request.use(function (config) {
  // Do something before request is sent
  const { user } = store.state
  // console.log(typeof user)
  // 如果用户已登陆,统一给接口设置token信息
  if (user) {
    // console.log(1)
    config.headers.Authorization = `Bearer ${user.token}`
    // console.log(config.headers.Authorization)
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})
export default request

react跨域配置:

在这里插入图片描述

方式(1):只能配置一个代理

要访问的路径:

http://localhost:5000/students

在package.json中添加代理代码:

"proxy":"http://localhost:5000"

此时访问的路径

 getStudentData = () => {
    axios.get('http://localhost:3000/students').then(
      Response => {
        console.log('成功了',Response.data)
      },
      error => {
        console.log('失败了')
      }
    )
  }

方式(2):可以配置多个代理

请求的路径:

http://localhost:5000
http://localhost:5001

如何配置:

在src目录下创建文件名为setupProxy.js的js文件,文件名字不可以修改
代码如下所示:
// react脚手架已经配置好了
const proxy = require('http-proxy-middleware')

module.exports = function (app) {
  app.use(
      proxy('/api1',{
          target:'http://localhost:5000',
          changeOrigin:true,
          pathRewrite:{'^/api1':''}
      }),
      proxy('/api2',{
        target:'http://localhost:5001',
        changeOrigin:true,
        pathRewrite:{'^/api2':''}
    })
  )
}

使用处:‘http://localhost:3000/api1/students’

axios.get('http://localhost:3000/api1/students').then(
      Response => {
        console.log('成功了',Response.data)
      },
      error => {
        console.log('失败了')
      }
    )

通过后端代码方式解决跨域问题:

response.setHeader(‘Access-Control-Allow-Origin’, ‘*’)加上这串代码来解决跨域

// 安装
// 1.引包
var express = require('express')
// 2.创建服务器应用程序
// 也就是原来的http.createserver
var app = express()
app.get('/', function (req, res) {
    // 这行代码的作用是允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*')
    res.end('hello express')
})

app.get('/about', function (req, res) {
    response.setHeader('Access-Control-Allow-Origin', '*')
    res.end('世界你好')
})

app.listen(8080, function () {
    console.log('app正在运行')
})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Realistic-er

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值