Reputation: 43
I'm an adjunct professor teaching a React/Mongoose course online. Last term many students started encountering problems either with CORS or 404 errors popping up on what was otherwise good code. I've been fighting for a solution for several weeks now.
First of all, when launching the app in Chrome 93.0.4577.63, all I get is a CORS error without any other helpful information that I can decypher: "Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information."
I am able to get further in Edge.
In case it makes any difference, the server.js file is in the root of the application, but the app code is located in a folder called "client". This is a portion of the /context/userProvider.js page in that client folder that is calling an axios function. The key portion of the code is the signup function().
import React, {useState} from "react";
import axios from "axios";
export const UserContext = React.createContext()
const userAxios = axios.create()
userAxios.interceptors.request.use(config => {
const token = localStorage.getItem("token")
config.headers.Authorization = `Bearer ${token}`
return config
})
export default function UserProvider(props){
const initState ={
user: JSON.parse(localStorage.getItem("user")) || {},
token: localStorage.getItem("token") || "",
comments: []
}
const [userState, setUserState] = useState(initState)
function signup(credentials){
axios.post("/auth/signup", credentials)
.then(res => {
const {user, token} = res.data
localStorage.setItem("token", token)
localStorage.setItem("user", JSON.stringify(user))
setUserState(prevUserState => ({
...prevUserState,
user,
token
}))
})
.catch(err => console.log(err))
}
I have the following line of code in the package.json file that sets the proxy to the port on which react is running:
"proxy": "http://localhost:9000"
Here is code from the server.js file that launches the mongoose server on port 9000:
app.use('/api', expressJwt({secret: process.env.SECRET, algorithms: ['RS256']}));
app.use('/auth', require("./routes/authRouter.js"));
app.use('/api/issue', require("./routes/issueRouter"));
app.use('/api/comment', require("./routes/commentRouter"));
app.use('/api/user', require("./routes/userRouter.js"))
app.use((err, req, res, next) => {
console.log(err)
if(err.name === "Unauthorized Error"){
res.status(err.status)
}
return res.send({errMsg: err.message})
});
app.listen(9000, () => {
console.log("The App is listening on port 9000")
});
When the user provides the user credentials on a fully functioning sign-up page, the credentials are successfully passed to the signup function, as shown from a console.log(credentials), but then I get the 404 error returned from the .catch portion of the signup function.
{username: 'csanders', password: 'chumisyum', firstName: 'chumbucket', lastName: 'sanders', phoneNumber: '1231231234'}
UserProvider.js:35 Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
When I run the same operation through Postman on port 3000, I get the following error.
<pre>Cannot POST /auth/signup</pre>
But when I run it through Postman on port 9000, it appears to work fine:
Can anyone give me any insight on either how to clear the CORS error in Chrome or how to get the 404 error in Edge to go away? I'm getting desperate!
Upvotes: 1
Views: 1668
Reputation: 264
I believe your proxy inside package.json file should point to your server, not to your react application itself.
"proxy": "http://www.yourapi.com"
Note: You should add the previous command in package.json within react application NOT the server and you need to restart your react app to take effect.
Using CORS in Express:
Also, you may enable CORS on the server side by adding CORS middleware to your server object.
1- install cors by npm or yarn:
npm install cors
2- append CORS to your server object:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
You can check the documentation for other cases like restricting access to specific origins:
http://expressjs.com/en/resources/middleware/cors.html
Upvotes: 1