【问题标题】:Sending data to and getting data from node.js?向node.js发送数据和从node.js获取数据?
【发布时间】:2019-11-17 11:33:37
【问题描述】:

在我的 React 代码中,我发送了一个“发布”和“获取”请求。我想我的问题出在我的服务器端代码上。

常规

const express = require('express');

const app = express();

const cors = require('cors');
const bodyParser = require('body-parser');

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

const posts = [
    {
        "postId": 1,
        "id": 1,
        "title": "To be or not to be",
        "body": "Yes, that is the question"
    },
    {
        "postId": 1,
        "id": 2,
        "title": "So What?",
        "body": "What do you want"
    }
];

注意:上下文,上面的代码在问题代码之前

已解决 1) 发布

用户点击“提交”一个发布请求将数据发送到服务器

问题:

1) “req.body”为空

fetch("http://localhost:3001/create", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(post)
    })
      .then(res => this.props.history.push('/posts'))
      .catch(err => this.setState({error: true}))

    this.setState({
      title: "",
      body: ""
    })
app.post('/create', (req, res, next)=>{
    // Request body is empty, why?
    console.log(req.body);
})

解决方案:

由于JSON.stringify(post),POST 请求正在以 JSON 格式发送数据,我们需要解析此 JSON 数据,以便我们可以使用app.use(bodyParser.json());,然后我们就有了。解决了

已解决 2) 获取

在第一个获取请求中,我将对象的“id”作为 URL 参数发送并尝试从服务器接收相应的对象,req 被正确发送。

问题:在“findPostById”函数中收到以下错误:

TypeError: 无法读取未定义的属性 id

fetch(`http://localhost:3001/posts/${this.props.match.params.id}`)
            .then(res=>res.json())
            .then(data=>this.setState({loadedPost: data}))
            .catch(err=>console.log(err))
app.get('/posts/:id', (req, res, next)=>{
    // Correct, receive id
    let id = req.params.id;

    findPostById(id, (post, err)=>{
        if(err){
            console.log(err);
        }
        else{
            res.send(post)
        }
    })
})

let findPostById = (id, cb)=>{
    console.log(id, 'Correctly receive the id');
    let post = posts.find((post)=>{
        return post.id === id;
    })
    // Receive: 'TypeError: Cannot read property id of undefined'
    console.log(post.id);
    if(post){
        cb(post, null);
    }
    else{
        cb(null, new Error('Could not find post', id));
    }
}

解决方案:

post.id 是 'number' 类型, id 是 'string' 类型,返回 post.id === id; 因为严格相等,所以返回 false。所以,我们用+id `return post.id === +id; 将id转换为数字;

【问题讨论】:

  • 尝试在获取请求中将密钥从“body”重命名为“postdata”。
  • For 1) 错误意味着post.id === id 永远不是true,因此posts.find 返回undefined。由于我们不知道posts 包含什么或id 的值是什么,因此我们无能为力。
  • 至于2),来自documentation"req.body包含请求体中提交的数据键值对,默认为undefined,为当您使用诸如 express.json()express.urlencoded() 之类的正文解析中间件时填充。" 所以看起来您没有正确设置中间件。
  • @FelixKling 是的,我确实使用 body-parser 库解析了“req.body”
  • @FelixKling 是的,posts.find 的错误是...但问题是什么?

标签: javascript reactjs express


【解决方案1】:

对于问题 1,

请尝试添加此内容。

app.use(bodyParser.json());

【讨论】:

  • 我试过不行。问题是我什至没有收到来自 POST 请求的数据,需要先解决这个问题,然后我们才能担心存储数据
  • 请尝试添加方法覆盖。 const methodOverride = require('method-override'), // 请求体解析中间件应该在 methodOverride app.use(bodyParser.urlencoded({extended: true })); app.use(bodyParser.json()); app.use(methodOverride());
  • 不需要将帖子转成JSON,只需要添加app.use(bodyParser.json());
【解决方案2】:

检查您的服务器端代码是否在配置下方丢失。

const bodyParser = require("body-parser");

app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ extended: false }));

body 解析器允许您从路由中访问 req.body

【讨论】:

    猜你喜欢
    • 2018-01-09
    • 2017-07-31
    • 1970-01-01
    • 2013-02-01
    • 2017-05-07
    • 2013-01-03
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    相关资源
    最近更新 更多