无法通过Node.js代理连接API,CORS问题仍存在求排查
CORS问题排查:Node代理后端仍拦截跨域请求
我在React组件中直接调用外部API时被CORS拦截,于是搭建了Node.js代理后端,但还是收到"cross-origin request blocked"错误,相关代码如下:
Node服务代码
const express = require('express'); const cors = require('cors'); const axios = require('axios'); const app = express(); const port = process.env.PORT || 3001; app.use(cors({ allowedHeaders: ['Authorization', 'Content-Type'], credentials: true })); app.get('/user', async (req, res) => { try { const response = await axios.get('https://demo.xxxxx.com/api/v2/user', { headers: { 'Authorization': 'Bearer xxxxxxx' }, }); res.header('Access-Control-Allow-Origin', '*'); res.send(response.data) } catch(err) { console.error(err); res.status(500).send(err) } }); app.listen(port, () => { console.log(`server listening on port ${port}`) })
React组件代码
import React, {useState, useEffect} from 'react' import data from './templates.json'; import Button from 'react-bootstrap/Button'; import axios from 'axios'; function Dashboard() { console.log(data) async function handleOnClick(){ try { const response = await axios.get("https://localhost:3001/user") console.log(response) } catch(err) { console.log(err) } } return ( <> <div>Dashboard</div> <Button onClick={handleOnClick}>Hello</Button> </> ) } export default Dashboard;
问题排查与修复方案
CORS配置冲突
你同时使用了cors中间件和手动设置Access-Control-Allow-Origin头,会导致响应头出现重复的跨域标识,浏览器判定为无效配置。直接删除res.header('Access-Control-Allow-Origin', '*');这一行,让cors中间件统一处理跨域头。credentials配置不兼容
当设置credentials: true时,Access-Control-Allow-Origin不能设为*,必须指定具体的前端域名(比如React项目通常运行在http://localhost:3000)。修改cors配置:app.use(cors({ origin: 'http://localhost:3000', // 替换为你的React实际运行域名 allowedHeaders: ['Authorization', 'Content-Type'], credentials: true }));如果不需要携带凭证(cookie、HTTP认证等),直接去掉
credentials: true即可。请求协议不匹配
确认Node服务的启动协议:如果是默认HTTP启动,前端请求要改成http://localhost:3001/user,而非https://localhost:3001/user,协议不匹配会导致请求失败,也可能被判定为跨域问题。验证服务可用性
先通过浏览器直接访问http://localhost:3001/user,确认服务正常启动且接口能返回数据,排除服务未启动或后端接口报错的情况。
内容的提问来源于stack exchange,提问作者Zak
相关产品推荐
相关产品推荐

