【问题标题】:POST http://localhost:9000/ net::ERR_CONNECTION_REFUSEDPOST http://localhost:9000/net::ERR_CONNECTION_REFUSED
【发布时间】:2019-12-23 11:21:39
【问题描述】:

我正在尝试通过发布请求向 api 发送一些数据。

前端代码(反应)

handleSubmit = e => {
    e.preventDefault();
    fetch("http://localhost:9000", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        title: this.state.title,
        text: this.state.text
      })
    });
  };

服务器(快递)

var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post("/", urlencodedParser, function(req, res) {
  sql = "INSERT INTO POSTS (id, title, text) VALUES ?";
  var values = [[uuidv1().toString(), req.body.title, req.body.text]];
  con.query(sql, [values], function(err, result, fields) {
    if (err) throw err;
  });
});

当我提交表单时,我从开发者控制台收到此错误消息

我在localhost:3000 上运行客户端,在localhost:9000 上运行服务器端。谁能告诉我这个问题是怎么发生的,我该如何解决?

【问题讨论】:

  • 要修复第一个错误,请参阅@Arturas 的答案,第二个您应该返回响应 res.send({result})

标签: javascript node.js reactjs api express


【解决方案1】:

在根目录下的 package.json 文件中添加如下代理属性:

{
    "proxy": "http://localhost:9000"
}

【讨论】:

  • 值得一提的是,仅当您使用 create-react-app 时才有效,也不要认为这与问题有关。
  • @Arturas 感谢您的回复。我试过了,但没有运气。值得一提的是,服务器在端口 9000 上运行良好,因为我在 bin/www 内有 var port = normalizePort(process.env.PORT || "9000");。此错误仅在发布请求被触发时发生。
【解决方案2】:

我找到了解决方案。显然没有发布数据。所以我必须用

替换标题
headers: {'Content-Type':'application/x-www-form-urlencoded'}

【讨论】:

  • 在哪里添加这一行,哪个文件?
猜你喜欢
  • 1970-01-01
  • 2021-03-30
  • 2021-12-16
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
相关资源
最近更新 更多