You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue与Node项目中的CORS跨域问题求助

Vue前端调用Node后端API遭遇CORS网络错误排查与解决

正在开发一个和The Grateful Dead相关的Vue网站,用curl测试Node后端API能正常获取响应,但前端调用时出现CORS网络错误,以下是相关代码和错误信息,求解决方向:

Vue组件代码

<script>
import axios from "axios";

export default {
  name: "About",
  data() {
    return {
      search: {
        year: null,
        state: "",
        city: "",
        song: "",
      },
      searchResults: [],
      error: null,
    };
  },
  methods: {
    async searchInfo() {
      try {
        const response = await axios.get("http://localhost:3000/api/setlist", {
          params: this.search,
        });

        this.searchResults = response.data;
        console.log("Updated searchResults:", this.searchResults);
      } catch (error) {
        console.error("Error fetching search results:", error);
      }
    },
  },
};
</script>

Node server.js代码

const express = require("express");
const axios = require("axios");
const cors = require("cors");

const app = express();
const PORT = process.env.PORT || 3000;


app.use(
  cors({
    origin: "*",
  })
);
app.get("/api/setlist", async (req, res) => {
  try {
    const { data } = await axios.get(
      "https://api.setlist.fm/rest/1.0/artist/6faa7ca7-0d99-4a5e-bfa6-1fd5037520c6/setlists",
      {
        headers: {
          Accept: "application/json",
          "x-api-key": "MY_API_KEY_TAKING_OUT_THE_ACTUAL_KEY",
        },
        params: req.query,
      }
    );
    res.json(data);
  } catch (error) {
    console.error("Error fetching Setlist API:", error);
    res.status(500).send("Error fetching data");
  }
});
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

控制台错误信息

Error fetching search results: 
AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
code
: 
"ERR_NETWORK"
config
: 
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
: 
"Network Error"
name
: 
"AxiosError"
request
: 
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
stack
: 
"AxiosError: Network Error\n    at XMLHttpRequest.handleError (http://localhost:5173/node_modules/.vite/deps/axios.js?v=4b244e95:1451:14)"
[[Prototype]]
: 
Error

点击错误提示显示:

Ensure CORS response header values are valid

setlist?year=1985&state=&city=&song=    blocked 

解决方向

  • 指定具体前端域名作为CORS origin:当前设置origin: "*",部分浏览器对通配符的兼容性有限,尤其是带参数的请求。可以改为指定前端实际运行的域名:
    app.use(
      cors({
        origin: "http://localhost:5173", // 匹配前端Vite默认端口
        credentials: true // 如果需要携带cookie可开启,当前场景可选
      })
    );
    
  • 过滤空请求参数:前端请求中包含year=null、state=这类空值参数,可能触发服务器或CORS中间件的异常处理。发送请求前过滤无效参数:
    async searchInfo() {
      try {
        // 过滤null和空字符串的参数
        const validParams = Object.fromEntries(
          Object.entries(this.search).filter(([key, val]) => val != null && val !== "")
        );
        const response = await axios.get("http://localhost:3000/api/setlist", {
          params: validParams,
        });
        this.searchResults = response.data;
        console.log("Updated searchResults:", this.searchResults);
      } catch (error) {
        console.error("Error fetching search results:", error);
      }
    },
    
  • 简化CORS配置测试:暂时去掉origin限制,直接使用app.use(cors()),确认是否是配置细节导致的问题。
  • 清除浏览器缓存:浏览器可能缓存了旧的CORS响应头,强制刷新页面(Ctrl+F5)或清除缓存后重新测试。
  • 检查中间件顺序:确保cors中间件在所有路由定义之前加载,当前代码已符合,但如果后续添加其他中间件,需注意顺序。

内容的提问来源于stack exchange,提问作者ashton8504

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:47:09