【问题标题】:issue with react ui communicating with nodereact ui与节点通信的问题
【发布时间】:2018-08-26 14:55:48
【问题描述】:

这是反应获取:

变种 JSON = { json: JSON.stringify({ 一个:1, 乙:2 }), 延迟:3 }; fetch('/saveInfo', { 方法:'发布', 标题:{ '接受':'应用程序/json,文本/纯文本,*/*', “内容类型”:“应用程序/json” }, 正文:JSON.stringify(json.json) }) .then(函数(响应){ 返回响应.json(); }) .then(函数(结果){ 警报(结果); console.log("文件已保存!"); }) .catch(函数(错误){ console.log('请求失败'); });

这是节点:

<pre>
var express = require('express');

module.exports = function(app) {
  var router = express.Router();

  router.get('/', function (req, res) {
    console.log('from node');
    console.log(req);


    res.json({status: 'UP'});
  });

  app.use("/saveInfo", router);
}
</pre>

上面的代码不适用于 fetch 的第二个参数。

但是当我执行它时不带第二个参数来获取如下:

fetch('/saveInfo')
     .then(function (response) {
         return response.json();
     })
     .then(function (result) {
         alert(result);
          console.log("The file was saved!");
     })
     .catch (function (error) {
         console.log('Request failed');
     });

工作正常,能够与节点程序通信。

谁能帮我解决这个问题。我想将 react 的 UI 表单状态发送给节点程序。

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    您还需要add a handler for the POST requests。
    在第一种情况的 fetch 方法中,您已将方法类型指定为 POST,但节点对此没有任何处理。
    但是,如果不给第二个参数,则认为是GET请求,被router.get拦截。
    只需在节点中添加这个(在 app.use 行之前):

    router.post("/", function (req, res) {
      console.log('from node');
      console.log(req);
      res.json({status: 'UP'});
    });
    

    它将使节点能够侦听 POST 请求。

    编辑:要访问 router.post 中的 post 请求正文参数,您需要 body-parser 包。安装此包并在初始化 express 路由器之前添加这两行:

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

    详细解释请阅读http://jilles.me/express-routing-the-beginners-guide/

    【讨论】:

    • 我也在尝试接收我在 UI 请求中发送的 json。
      body: JSON.stringify(json.json)
      。如何获取 router.post 处理程序中的值。我正在尝试使用未定义的 req.body 。 req.params 哪个是空白的?
    • 你需要 body-parser 包。 app.use(bodyParser.json())app.use(bodyParser.urlencoded({ extended: false }))。在初始化快速路由器之前安装软件包并添加这些行。详细解释请阅读jilles.me/express-routing-the-beginners-guide。
    • 那么我建议你也阅读一下:What should I do when someone answers my question?
    猜你喜欢
    • 2017-10-16
    • 2017-09-14
    • 1970-01-01
    • 2020-11-28
    • 2020-06-30
    • 2021-01-10
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多