react-create-app调用Node API出现403错误,请求协助解决
Hey there, let's break down why you're hitting that 403 error and fix it step by step!
1. Auth Middleware is Blocking Your Signup Request
The most direct cause of your 403 is that you've added the auth middleware to your signup route—but signup is meant for unauthenticated users! The middleware is checking for a valid auth token (which you don't have yet during signup) and rejecting the request with a 403.
Fix your route by removing the auth middleware:
const express = require('express'); const userController = require('../controllers/user'); const auth = require('../middlewares/auth'); const api = express.Router(); // Remove the auth middleware from signup api.post('/signup', userController); module.exports = api;
2. Frontend Fetch Request is Missing Critical Headers
Your fetch call has two issues that will break functionality even after fixing the 403:
- There's no
Content-Type: application/jsonheader, so Express can't parse your JSON body correctly. dataType: 'json'is a jQuery-specific option—fetch doesn't recognize it.
Here's the corrected frontend code:
let response = await fetch('http://localhost:3001/api/signup', { method: 'POST', headers: { 'Content-Type': 'application/json', // Required for JSON payloads }, body: JSON.stringify(data) });
3. Backend Controller Has Broken Logic
Even if you fix the 403, your controller will throw errors that break the flow:
- Typo:
service.createTokenshould beservices.createToken(you importedservices, notservice). - No error response to frontend: If saving the user fails, you only log the error to the console—your frontend will hang waiting for a response.
createTokenis a function (I assume) so you need to call it, probably with the saved user as an argument.
Corrected controller code:
const User = require('../models/user'); const mongoose = require('mongoose'); const services = require('../services'); function signUp(req, res) { const user = new User({ name: req.body.name, email: req.body.email, password: req.body.password }); user.save((err, savedUser) => { if (err) { console.log(err); // Send error response to frontend instead of just logging return res.status(500).send({ error: 'Failed to create user account' }); } // Call createToken with the saved user (adjust argument if your function expects something else) res.status(201).send({ token: services.createToken(savedUser) }); }); } module.exports = signUp;
4. Proxy Configuration (If You Want to Use It)
If you still want to use the proxy setup in package.json, make sure it's configured correctly:
"proxy": "http://localhost:3001"
Then update your fetch call to use a relative path:
let response = await fetch('/api/signup', { /* ... */ });
Note: You'll need to restart your frontend development server after changing the proxy setting for it to take effect.
内容的提问来源于stack exchange,提问作者Khantus

