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

React调用Node.js后端POST请求出现跨域协议错误求助

Fixing the Cross-Origin Error When Calling Node.js Backend from React

Hey there, let's work through this cross-origin error you're seeing—it's one of the most common gotchas when connecting a React frontend to a Node backend, so don't worry, we'll get it sorted!

First: Check Your Request URL

The error message explicitly states cross-origin requests only support schemes like http, https, etc. Looking at your failed request URL (localhost:3000/doctors/register), the root issue might be that you're missing the protocol prefix (http://).

Browsers treat URLs without a protocol as relative paths or non-standard schemes, which immediately triggers this cross-origin block. Update your request URL to include the full protocol:

// ❌ Wrong
axios.post('localhost:3000/doctors/register', yourFormData)

// ✅ Correct
axios.post('http://localhost:3000/doctors/register', yourFormData)

Second: Enable CORS on Your Node.js Backend

Even if your URL is fixed, if your React app runs on a different port (React defaults to 3000, while your Node backend might use 5000 for example) or domain, browsers block cross-origin requests by default. You need to configure CORS (Cross-Origin Resource Sharing) on your Node server to allow requests from your React app.

Here's how to set this up with Express (the most popular Node framework):

  1. Install the cors package:
npm install cors
  1. Import and enable it in your server file:
const express = require('express');
const cors = require('cors');
const app = express();

// Allow all origins (great for development)
app.use(cors());

// For production, restrict to your React app's specific origin
// app.use(cors({
//   origin: 'http://localhost:3000'
// }));

// Your registration route and other logic
app.post('/doctors/register', (req, res) => {
  // Handle registration logic here
});

app.listen(3000, () => console.log('Server running on port 3000'));

Quick Troubleshooting Checklist

  • Double-check that your Node server is actually running on the port you're targeting (e.g., 3000).
  • If you're using fetch instead of axios, the same URL rule applies—always use the full protocol + host + path.
  • Clear your browser cache occasionally, as old cached settings can cause unexpected cross-origin glitches.

Give these steps a try, and your POST request should start working as expected!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:05:49