Vue3项目使用axios调用后端接口解决跨域且部署服务器nginx相关跨域配置

Vue3项目使用axios调用后端接口解决跨域且部署服务器nginx相关跨域配置


一、Vue中配置

在使用 Vue 3 中的 Axios 发起跨域请求时,你可能需要进行一些配置来解决跨域访问的问题。以下是一种解决方法:

  1. 在项目的根目录下新建一个 vue.config.js 文件(如果没有的话)。

  2. vue.config.js 文件中添加如下内容:

module.exports = defineConfig({
  transpileDependencies: true,
  //解决跨域
  devServer: {
    // host: '127.0.0.1',  // 此前端项目的IP地址
    // port: 8010,  // 此前端项目的端口号
    // open: true,  //表示在启动开发服务器时,会自动打开浏览器并访问指定的地址
    proxy: {
      '/dockingApi': {
        target: 'http://127.0.0.1:8888/', //接口域名
        changeOrigin: true,       //是否跨域
        pathRewrite: {
          '^/dockingApi': ''  //假如我们的地址是 /dockingApi/member/getToken 会转化为 /member/getToken
        }
      }
    }
  }
})

在上面的例子中,我们通过 devServerproxy 配置来设置代理,将所有以 /api 开头的请求代理到后端接口地址,并且启用了跨域。请将 target 的值替换为你实际的后端接口地址。

  1. 然后在 Axios 请求时,只需要写相对路径即可,如:
axios.get('/dockingApi/data')  // 实际请求会被代理到 http://127.0.0.1:8888/data

1、代码举例

<template>
  <div style="margin-left: 10%; text-align: left">
    <div style="margin-top: 20px">
      <el-input
        v-model="IDNumber"
        style="width: 240px"
        placeholder="请输入身份证号"
      />
    </div>
    <div style="margin-top: 20px">
      <el-button @click="queryLadderControl()" type="primary" round
        >查询</el-button
      >
    </div>
  </div>
</template>
<script setup>
import { ref } from "vue";
import axios from "axios";

const IDNumber = ref();
const queryLadderControl = async () => {
  try {
    const response = await axios.get(
      "dockingApi/xxxxxx/xxxxx?IDCard=" +
        IDNumber.value
    );
    // 假设接口返回的数据中有一个字段叫做 id
    const id = response.data.id;
    console.log("response=", response);
    // 跳转到指定页面,并且将数据作为参数传递
    // router.push({ path: "/target-page", query: { id } });
  } catch (error) {
    console.error("获取数据失败", error);
  }
};
</script>

二、Nginx中配置

		location /dockingApi/ {
          proxy_pass http://10.0.0.81:8888/;   # 后端服务器域名和端口(开发环境)
          proxy_set_header Host $proxy_host;
      } 

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    
    sendfile        on;

    keepalive_timeout  65;


    server {
        listen       8010;
        server_name  localhost;

        location / {
            root   dist;
            index  index.html index.htm;
			try_files $uri $uri/ /index.html;
        }
		
		# 对应代理其中10.0.0.81是后端对应地址
		location /dockingApi/ {
          proxy_pass http://10.0.0.81:8888/;   # 后端服务器域名和端口(开发环境)
          proxy_set_header Host $proxy_host;
      } 

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }


    }
}

这样就可以解决 Vue 3 中使用 Axios 发起跨域请求的问题。希望对你有所帮助!

  • 31
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

和烨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值