问题
Well, there are lots of questions in StackOverflow about this error I've seen all of them none of them is working for me. I'm using react with redux trying to fetch some products. my backend server node is running on port 5000 and I'm using concurrently to start both servers at the same time whenever I'm trying fetch the data its using port 3000 where is my frontend running. Please somebody help me to solve this issue
package.json file
{
"name": "proshop",
"version": "1.0.0",
"description": "MERN application named proshop",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node backend/server",
"server": "nodemon backend/server",
"client": "npm start --prefix frontend",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"data:import": "node backend/seeder",
"data:destroy": "node backend/seeder -d"
},
"keywords": [
"NodeJS",
"ExpressJs",
"React",
"Redux",
"MongoDb"
],
"author": "Narayan Maity",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"colors": "^1.4.0",
"concurrently": "^5.3.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-async-handler": "^1.1.4",
"mongoose": "^5.10.9"
},
"devDependencies": {
"nodemon": "^2.0.6"
}
}
Here is my productsAction.js file
import axios from 'axios';
import {
PRODUCT_LIST_FAIL,
PRODUCT_LIST_REQUEST,
PRODUCT_LIST_SUCCESS,
} from '../constants/productConstants';
export const listProducts = () => async (dispatch) => {
try {
dispatch({ type: PRODUCT_LIST_REQUEST });
const { data } = await axios.get('http://localhost:5000/api/products');
dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
} catch (error) {
dispatch({
type: PRODUCT_LIST_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
If I use the full address like HTTP://localhost:5000/api/products its giving me CORS error
回答1:
It would be much more easier and focus
if you add "proxy": "http://localhost:5000"
in your client
or react
project folder, like so:-
client/package.json
{
"name": "projectname",
"version": "0.1.0",
"private": true,
"dependencies": {
...}
"proxy": "http://localhost:5000"
}
Then you can just do:-
await axios.get('/api/products') // straight away use whatever path you've specified
来源:https://stackoverflow.com/questions/64767422/i-am-getting-an-error-get-http-localhost3000-api-products-404-not-found