获取net :: err_connection_reset,并且在提出发布请求时无法获取

发布于 2025-02-04 15:15:50 字数 3845 浏览 2 评论 0原文

我有一个react.js任务,要求我向服务器提出发布请求。现在,当用户单击提交按钮时,我想发送发布请求。但是我一直遇到这两个错误:

App.js:19 POST http://localhost:3001/ net::ERR_CONNECTION_RESET
App.js:19 Uncaught (in promise) TypeError: Failed to fetch at handleSubmit (App.js:19:1)

我的反应代码:

import "./App.css";

function App() {
  const [inputs, setInputs] = useState({});
  const [backendData, setBackendData] = useState();

  const handleChange = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    setInputs((state) => ({ ...state, [name]: value }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    /*when submit is clicked, we are goint to send a POST request so that data of the inputs is created*/
    console.log(inputs);
    fetch("http://localhost:3001/", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(inputs),
    });
  };

  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          name="projectTitle"
          onChange={handleChange}
          className="project-title"
          value={inputs.projectTitle || " "}
        />
        <input
          type="text"
          name="id"
          className="id"
          onChange={handleChange}
          value={inputs.id || " "}
        />
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}

export default App;

我的明确代码:

const express = require("express");
const app = express();
const fs = require("fs");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

var obj = { projects: [] };
app.post("/", (req, res, next) => {
  let identifier = req.query.identify; //id of project

  fs.readFile("webProjects.json", (err, data) => {
    if (err) throw err;
    obj = JSON.parse(data);
    obj.projects.push({
      id: identifier,
      title: req.query.project,
      description: req.query.description,
    });
    let json = JSON.stringify(obj);
    fs.writeFile("webProjects.json", json, (err) => {
      if (err) throw err;
      console.log("updatedd", req.body.inputs);
    });
  });
});

/*when user sends delete request, delete specific data.*/
app.delete("/", (req, res, next) => {
  fs.readFile("webProjects.json", (err, data) => {
    console.log(data);
    obj = JSON.parse(data);

    // assign the filtered array back to the original array
    obj.projects = obj.projects.filter((item) => {
      let url = req.query.identify;
      return item.id !== url;
    });

    console.log(obj);
    let json = JSON.stringify(obj);
    fs.writeFile("webProjects.json", json, (err) => {
      if (err) throw err;
      console.log(obj);
    });
  });
});

/*when user navigates to another page, we display the data of the resource*/
app.get("/api", (req, res, next) => {
  fs.readFile("webProjects.json", (err, data) => {
    if (err) throw err;
    res.json(JSON.parse(data));
    console.log("done");
  });
});

/*we want to catch all errors, with the requests made to the server.
used the wildcard(*) to make sure that we catch all requests made to the server.
*/
app.get("*", (req, res, next) => {
  let err = new Error("There was an error in accessing the page you wanted");
  err.statusCode = 404;
  next(err);
});

app.use((err, req, res, next) => {
  console.log(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

let PORT = process.env.PORT || 3001;

app.listen(PORT, () => {
  console.log("server has listened");
});

I have a React.js task that requires me to make a POST request to the server. Now, I want to send a POST request when a user clicks a submit button. But I keep getting these 2 errors:

App.js:19 POST http://localhost:3001/ net::ERR_CONNECTION_RESET
App.js:19 Uncaught (in promise) TypeError: Failed to fetch at handleSubmit (App.js:19:1)

My React code:

import "./App.css";

function App() {
  const [inputs, setInputs] = useState({});
  const [backendData, setBackendData] = useState();

  const handleChange = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    setInputs((state) => ({ ...state, [name]: value }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    /*when submit is clicked, we are goint to send a POST request so that data of the inputs is created*/
    console.log(inputs);
    fetch("http://localhost:3001/", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(inputs),
    });
  };

  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          name="projectTitle"
          onChange={handleChange}
          className="project-title"
          value={inputs.projectTitle || " "}
        />
        <input
          type="text"
          name="id"
          className="id"
          onChange={handleChange}
          value={inputs.id || " "}
        />
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}

export default App;

My Express code:

const express = require("express");
const app = express();
const fs = require("fs");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

var obj = { projects: [] };
app.post("/", (req, res, next) => {
  let identifier = req.query.identify; //id of project

  fs.readFile("webProjects.json", (err, data) => {
    if (err) throw err;
    obj = JSON.parse(data);
    obj.projects.push({
      id: identifier,
      title: req.query.project,
      description: req.query.description,
    });
    let json = JSON.stringify(obj);
    fs.writeFile("webProjects.json", json, (err) => {
      if (err) throw err;
      console.log("updatedd", req.body.inputs);
    });
  });
});

/*when user sends delete request, delete specific data.*/
app.delete("/", (req, res, next) => {
  fs.readFile("webProjects.json", (err, data) => {
    console.log(data);
    obj = JSON.parse(data);

    // assign the filtered array back to the original array
    obj.projects = obj.projects.filter((item) => {
      let url = req.query.identify;
      return item.id !== url;
    });

    console.log(obj);
    let json = JSON.stringify(obj);
    fs.writeFile("webProjects.json", json, (err) => {
      if (err) throw err;
      console.log(obj);
    });
  });
});

/*when user navigates to another page, we display the data of the resource*/
app.get("/api", (req, res, next) => {
  fs.readFile("webProjects.json", (err, data) => {
    if (err) throw err;
    res.json(JSON.parse(data));
    console.log("done");
  });
});

/*we want to catch all errors, with the requests made to the server.
used the wildcard(*) to make sure that we catch all requests made to the server.
*/
app.get("*", (req, res, next) => {
  let err = new Error("There was an error in accessing the page you wanted");
  err.statusCode = 404;
  next(err);
});

app.use((err, req, res, next) => {
  console.log(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

let PORT = process.env.PORT || 3001;

app.listen(PORT, () => {
  console.log("server has listened");
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷你仙 2025-02-11 15:15:50

如果使用create-react-app命令创建前端,则问题可能是代理。在您的package.json文件中,您可以添加代理,如下所示:

 "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:3001"

If the front end is created with create-react-app command, the problem might be the proxy one. In your package.json file, you can add proxy as shown below:

 "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:3001"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文