Express API与React前端交互问题:请求头未发送Cookie
问题分析
核心问题是跨域请求中Cookie未被正确携带,前后端的跨域配置和Fetch请求设置存在错误,导致浏览器出于安全策略阻止了Cookie的发送。
前端(React)修改方案
调整Fetch请求配置,移除无效请求头并添加凭证携带选项:
export default function ApiData() { const [usr,setUsr] = useState([]) useEffect(()=>{ fetch('http://localhost:8080',{ headers: { 'accept': 'application/json' }, // 关键:允许跨域请求携带Cookie credentials: 'include' }) .then(res => res.json()) .then(data => { setUsr(data) console.log(data) }) .catch(err => console.error('请求错误:', err)) },[]) return( <div> {usr.badRequest} {usr.name} </div> ) }
说明:
credentials: 'include'会让Fetch自动携带当前域名下的Cookie,无需手动设置Cookie请求头(手动设置会被浏览器安全策略拦截)。- 移除了
Access-Control-Allow-Origin和origin请求头,这两个是后端响应或浏览器自动处理的内容,前端手动设置无效。
后端(Express)修改方案
调整CORS配置,允许携带凭证并指定具体前端域名:
// 定义正确的CORS配置 const corsOptions = { // 替换为你的React应用实际运行地址,比如http://localhost:3000 origin: 'http://localhost:3000', // 允许跨域请求携带凭证 credentials: true }; app.get('/', cors(corsOptions), async (req,res) => { if (req.headers.cookie) { let ck = req.headers.cookie.split('=') const sendData = await mysql( 'list', ck[1] ) res.json( sendData[0] ) }else{ res.json( {badRequest:'cookie is not defined'} ) } })
说明:
- 当
credentials: true时,origin不能设为*,必须指定具体前端域名,否则浏览器会拒绝接收响应。- 后端开启
credentials后,才允许跨域请求携带Cookie。
额外注意事项
- 确保Cookie的
domain和path设置正确,匹配当前请求的域名;若为HTTP-only Cookie,document.cookie无法获取,但Fetch仍会自动携带。 - 测试时可在浏览器开发者工具的「网络」面板查看请求头,确认
Cookie字段是否存在。
内容的提问来源于stack exchange,提问作者Jhow
相关产品推荐
相关产品推荐

