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

Vue.js/Nuxt.js项目调用API遇CORS问题求助

解决Vue.js/Nuxt.js项目中请求Arianlist API的CORS问题

问题描述

"Access to XMLHttpRequest at 'https://app.arianlist.com/api/public/items/index/book' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

你的Express代理没正确处理CORS预检请求(OPTIONS),且当前响应头设置逻辑存在问题,导致浏览器依然拦截请求。

修正后的代理配置

以下是调整后的代理代码,可解决预检请求失败和响应头缺失问题:

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors');

const app = express();
const PORT = 3000;

// 先启用CORS中间件处理预检请求
app.use(cors({
  origin: 'http://localhost:3000', // 明确指定前端源,比通配符*更安全
  credentials: true
}));

const apiProxy = createProxyMiddleware('/api', {
  target: 'https://app.arianlist.com',
  changeOrigin: true,
  pathRewrite: {
    '^/api': '/api', // 原API路径包含/api前缀,此处不能清空,否则会导致请求路径缺失/api部分
  },
});

app.use('/api', apiProxy);

app.listen(PORT, () => {
  console.log(`Proxy server is running on http://localhost:${PORT}`);
});

关键修改说明

  • 添加cors中间件:专门处理OPTIONS预检请求,自动生成符合规范的CORS响应头,这是解决预检失败的核心。
  • 修正pathRewrite规则:原API目标路径包含/api前缀,若前端请求路径是/api/public/items/index/book,需保持前缀映射一致,否则代理后的请求会变成https://app.arianlist.com/public/items/index/book,导致路径错误。
  • 指定具体origin:用http://localhost:3000替代*,同时开启credentials,适合需要携带cookie或认证信息的请求场景。

前端请求调整

确保Vue/Nuxt项目的API请求指向代理服务器,示例如下:

  • Nuxt项目可在nuxt.config.js中配置axios:
export default {
  axios: {
    baseURL: 'http://localhost:3000/api'
  }
}
  • Vue组件内直接请求:
axios.get('/api/public/items/index/book')

额外注意事项

  • 需先安装cors依赖:执行npm install cors或yarn add cors。
  • 若问题仍存在,可查看浏览器Network面板,确认请求是否正确转发到代理服务器,以及代理后的请求URL是否符合预期。

内容的提问来源于stack exchange,提问作者faeze.fd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 16:45:04