我收到错误 GET http://localhost:3000/api/products 404(未找到) [英] I am getting an error GET http://localhost:3000/api/products 404 (Not Found)

查看:76
本文介绍了我收到错误 GET http://localhost:3000/api/products 404(未找到)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,StackOverflow 中有很多关于此错误的问题,我已经看到了所有问题,但没有一个对我有用.我正在使用 react with redux 尝试获取一些产品.我的后端服务器节点在端口 5000 上运行,每当我尝试使用端口 3000 获取数据时,我都会同时使用以同时启动两台服务器,我的前端正在运行.请有人帮我解决这个问题

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

{
  "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"
  }
}

这是我的 productsAction.js 文件

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,
    });
  }
};

如果我使用像 HTTP://localhost:5000/api/products 这样的完整地址,它会给我 CORS 错误

推荐答案

如果添加 "proxy":"http://localhost,会更容易和 focus:5000" 在您的 clientreact 项目文件夹中,如下所示:-

It would be much more easier and focus if you add "proxy": "http://localhost:5000" in your client or react project folder, like so:-

{
  "name": "projectname",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
  ...}
  "proxy": "http://localhost:5000"
}

然后你可以这样做:-

await axios.get('/api/products') // straight away use whatever path you've specified

这篇关于我收到错误 GET http://localhost:3000/api/products 404(未找到)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆