Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 节点/反应客户端代理不工作,componentDidMount()未获取数据_Node.js_Reactjs_Express_Axios - Fatal编程技术网

Node.js 节点/反应客户端代理不工作,componentDidMount()未获取数据

Node.js 节点/反应客户端代理不工作,componentDidMount()未获取数据,node.js,reactjs,express,axios,Node.js,Reactjs,Express,Axios,编辑:可以找到指向项目回购的链接 当我的个人资料页面加载到React应用程序时,我正在尝试获取数据。 我的客户端运行在localhost:3000上,服务器运行在localhost:5000上 我的客户机文件夹package.json中还有一个代理,它指向localhost:5000(假定)。 在我的服务器文件中,我还有COR,以及我过去使用过的所有常用的铃铛和口哨 每当我的组件挂载时,在我的控制台中,我会收到一个404错误,说我的get请求失败,它说它试图访问localhost:3000/re

编辑:可以找到指向项目回购的链接

当我的个人资料页面加载到React应用程序时,我正在尝试获取数据。 我的客户端运行在localhost:3000上,服务器运行在localhost:5000上

我的客户机文件夹package.json中还有一个代理,它指向localhost:5000(假定)。 在我的服务器文件中,我还有COR,以及我过去使用过的所有常用的铃铛和口哨

每当我的组件挂载时,在我的控制台中,我会收到一个404错误,说我的get请求失败,它说它试图访问localhost:3000/recipes-根据我的代理,这是错误的,因为它应该向localhost:5000发出请求

然而,它变得更加棘手,因为为了测试它,我更改并硬编码了我的路由为localhost:5000,但即使这样也返回了404错误

起初,我认为我的后端GET请求逻辑有问题,但问题是,当我将生成GET请求的同一个函数粘贴到componentDidUpdate()中时,它成功地获取了所有的配方(这是一个配方应用程序),只是它触发了一个无限循环并变得疯狂,显然我无法做到这一点

有人知道这是怎么回事吗?为什么我的getRecipes()函数(发出get请求)在componentDidMount()内部不工作,出现404错误,无法成功代理,但在componentDidUpdate()内部工作?为什么是无限循环

这是我的前端代码:

import React, { Component } from "react";
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input
} from "reactstrap";
import styles from "./RecipeList.module.css";
// import { addRecipe } from "../RecipeFunctions/RecipeFunctions";
import axios from "axios";
import RecipeItem from "../RecipeItem/RecipeItem";
import jwt_decode from "jwt-decode";

export default class RecipeList extends Component {
  state = {
    recipes: [],
    modal: false,
    email: "",
    recipeName: "",
    ingredients: "",
    directions: "",
    errors: {
      msg: ""
    }
  };

  toggle = () => {
    this.setState({
      modal: !this.state.modal
    });
  };

  onChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  onSubmit = e => {
    e.preventDefault();

    const newRecipe = {
      user_email: this.state.email,
      title: this.state.recipeName,
      ingredients: this.state.ingredients,
      directions: this.state.directions
    };

    // Make Post Request w/ Axios from RecipeFunctions.js
    this.addRecipe(newRecipe);
    this.getRecipes();
  };

  getRecipes = () => {
    axios.get(`/recipes/${this.state.email}`).then(res => {
      this.setState({
        recipes: res.data
      });
    });
  };

  addRecipe = newRecipe => {
    axios.post("/recipes", newRecipe).then(response => {
      console.log("Recipe added.");
      console.log(this.state.email)
    });
  };

  deleteRecipe = id => {
    axios
      .delete(`/recipes/${id}`)
      .then(this.getRecipes())
      .catch(err => console.log(err));
  };

  viewRecipe = id => {
    axios
      .post(`/viewrecipe/${id}`)
      .then(this.getRecipes())
      .catch(err => console.log(err));
  };

  closeRecipe = id => {
    axios
      .post(`/closerecipe/${id}`)
      .then(this.getRecipes())
      .catch(err => console.log(err));
  };

  componentDidMount() {
    try {
      const token = localStorage.usertoken;
      const decoded = jwt_decode(token);
      this.setState({
        firstname: decoded.firstname,
        lastname: decoded.lastname,
        email: decoded.email
      });
    } catch {
      this.setState({
        errors: {
          msg: "You must be logged in to see your profile."
        }
      });
    }
    this.getRecipes();
  }

  render() {
    if (this.state.email) {
      return (
        <div id={styles.compWrapper} className="container">
          <div>
            <div id={styles.titleWrapper} className="col-sm-8 mx-auto">
              <h1 className="text-center">{this.state.firstname}'s Cookbook</h1>
            </div>
            <div className="text-center">
              <div>
                <Button
                  id={styles.addRecipeBtn}
                  outline
                  color="secondary"
                  onClick={this.toggle}
                  size="sm"
                >
                  Add Recipe
                </Button>
                <div className={styles.feedWrapper}>
                  <Modal
                    className={styles.addRecipeModal}
                    isOpen={this.state.modal}
                    toggle={this.toggle}
                  >
                    <ModalHeader toggle={this.toggle}>New Recipe</ModalHeader>
                    <ModalBody>
                      <Form onSubmit={this.onSubmit}>
                        <FormGroup>
                          <Label for="item">Recipe Name</Label>
                          <Input
                            type="text"
                            name="recipeName" // *must match this.state above
                            id="item"
                            placeholder="ex. Chicken Pot Pie"
                            onChange={this.onChange}
                          />
                          <Label className={styles.inputLabel} for="item">
                            Ingredients
                          </Label>
                          <Input
                            type="textarea"
                            size="lg"
                            name="ingredients" // *must match this.state above
                            id={styles.ingredientsTextArea}
                            onChange={this.onChange}
                          />
                          <Label className={styles.inputLabel} for="item">
                            Directions
                          </Label>
                          <Input
                            type="textarea"
                            size="lg"
                            name="directions" // *must match this.state above
                            id={styles.directionsTextArea}
                            onChange={this.onChange}
                          />
                          <Button
                            color="dark"
                            style={{ marginTop: "2rem" }}
                            block
                            onClick={this.toggle}
                          >
                            Add
                          </Button>
                        </FormGroup>
                      </Form>
                    </ModalBody>
                  </Modal>
                </div>
                <div
                  id={styles.recipeListWrapper}
                  className="recipe-list-container"
                >
                  {this.state.recipes.map(recipe => (
                    <RecipeItem
                      id={recipe._id}
                      title={recipe.title}
                      ingredients={recipe.ingredients}
                      directions={recipe.directions}
                      beingViewed={recipe.beingViewed}
                      viewRecipe={this.viewRecipe}
                      closeRecipe={this.closeRecipe}
                      deleteRecipe={this.deleteRecipe}
                    />
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      );
    } else {
      return (
        <p className="text-center jumbotron mt-5">{this.state.errors.msg}</p>
      );
    }
  }
}
如有必要,以下是实际路线(“配方”。是以/配方为基础的express router):


感谢您的帮助

在获取请求中,尝试使用192.168.17.161:5000而不是localhost:5000

代码在哪里?在git hub中推送代码并共享链接。@Arjun刚刚做了,链接位于顶部。尝试将axios.get(“/recipes”)替换为axios.get(“)@Arjun不确定您要查找的位置,但客户端在package.json中确实有react脚本。并且刚刚添加了localhost:5000以获取请求,现在我得到了:net::ERR\u CONNECTION\u refered完整的错误消息是什么?是cors问题吗?您可以解释一下吗?当您编写localhost时,它将调用您的localhost机器,在浏览器存在的地方,您可以n创建本地主机的子域并使用它,或者您可以使用应用程序所在的地址。您可以使用ipconfig检查它,如果默认情况下不是这样。192.168.17.161Ok将尝试它,看看它是否有助于故障排除
const express = require("express");
const path = require('path');
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(cors());
app.use(
  bodyParser.urlencoded({
    extended: false
  })
);

dotenv.config();
const db = process.env.DB_CONNECT;

const Users = require("./routes/Users");
const Recipes = require("./routes/Recipes");

app.use("/users", Users);
app.use("/recipes", Recipes);

mongoose
  .connect(db, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useCreateIndex: true
  })
  .then(() => console.log("MongoDB Connected..."))
  .catch(() => console.log(err));

app.post("/viewrecipe/:id", (req, res) => {
  Recipe.findOneAndUpdate({ _id: req.params.id }, { $set: { beingViewed: true } })
    .then(res.send("Recipe being viewed."))
    .catch(err => console.log(err));
});

app.post("/closerecipe/:id", (req, res) => {
  Recipe.findOneAndUpdate({ _id: req.params.id }, { $set: { beingViewed: false } })
    .then(res.send("Recipe closed."))
    .catch(err => console.log(err));
});

app.get("/showrecipes", (req, res) => {
  Recipe.find({}).then(recipes => res.send(recipes));
});

app.delete("/deleterecipes", (req, res) => {
  Recipe.deleteMany({}).then(res.send("All recipes deleted. Database empty."));
});

// Serve static assets if in production
if(process.env.NODE_ENV === 'production') {
  // Set static folder
  app.use(express.static('client/build'));

  app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
recipes.get("/:useremail", (req, res) => {
  if (!req.params.useremail) {
    res.send("You must be logged in to access recipes.");
  }
  Recipe.find({
    user_email: req.params.useremail
  })
    .then(recipes => {
        res.send(recipes)
    .catch(err => {
      res.send("error: " + err);
    });
});