一. 使用axios调用后端接口

  1. 安装axios:cnpm install axios
  2. 使用axios调用接口
getById = (id) => {
    axios.get('http://localhost:8080/api1/accountCustomer/getAccountCustomerByAccountIDAsyn?id="+id).then(
        response => {console.log('请求成功', response.data)},
        error => {console.log('请求失败', error)}
    )
}
  1. 在项目中访问后端接口出现跨域
    在这里插入图片描述
    二. 解决方案
    方案一:在package.json中添加配置
"proxy": "http://localhost:8080"

在这里插入图片描述
说明:
1. 优点:配置简单,前端请求资源时可以不加任何前缀。
2. 缺点:不能配置多个代理。
3. 工作方式:上述配置代理,当请求了3000不存在的资源,那么该请求就会转发给8080(优先匹配前端资源)。

方案二:创建代理配置文件:在src目录下创建配置文件(路径和文件名必须完全一致):src/setupProxy.js
在这里插入图片描述

const proxy = require('http-proxy-middleware')

module.exports = function (app) {
    app.use(
        proxy('/api1', {  // 遇见/api1的前缀,就会触发该代理
            target: 'http://localhost:8080',  // 请求转发给谁
            // 控制服务器中收到响应头的Hostz字段的值:
            // 如果为true,那么就是localhost:8080,如果为false,那么就是localhost:3000
            changeOrigin: true,
            // 重写该路径,因为前端访问8080的请求路径必须为http://localhost:3000/api/getById,
            // 但是服务器没有这个请求,所以相当于把路径上得api替换成了空字符串
            pathRewrite: {'^/api1': ''}
        }),
        proxy('/api2', {
            target: 'http://localhost:8081',
            changeOrigin: true,
            pathRewrite: {'^/api2': ''}
        })
    )
}
注意:如果使用了方案二,那么请求的路径必须加前缀。
比如使用上方的配置,访问接口必须变成以下方式(添加api1的前缀):(此时已经不需要写localhost这些前缀了,配置后由代理进行匹配)
getById = (id) => {
    axios.get('api1/accountCustomer/getAccountCustomerByAccountIDAsyn?id="+id).then(
        response => {console.log('请求成功', response.data)},
        error => {console.log('请求失败', error)}
    )
}

说明:

  1. 优点:可以配置多个代理,可以灵活的配置请求是否走代理。
  2. 缺点:配置繁琐,前端请求资源时必须加前缀。

配置之后就可以成功了

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐