【问题标题】:React, data sent to backend in req.body, can't use fields form req.bodyReact,req.body中发送到后端的数据,不能使用req.body中的字段
【发布时间】:2019-01-01 20:51:06
【问题描述】:

我正在构建 React/Node/Stripe 应用程序,基本设置工作正常,但是当我想扩展我的应用程序以从输入表单收集电子邮件地址并将其以正文发送到节点后端以使用它来创建客户或发送电子邮件时。我在 console.log 中看到 req.body 中存在电子邮件,但我可以获取此字段。

反应

电子邮件已收集

 import React, { Component } from "react";
import { CardElement, injectStripe } from "react-stripe-elements";
import styled from "styled-components";






    class CheckoutForm extends Component {
      constructor(props) {
        super(props);
        this.state = {
          complete: false,
          name: "",
          email: ""
        };
      }
      handleChange = input => e => {
        this.setState({
          [input]: e.target.value
        });
        console.log(this.state.email);
      };
   submit = async () => {
    let { token } = await this.props.stripe.createToken({
      name: this.state.name,
      email: this.state.email
    });
    console.log(token);
    const email = this.state.email;
    const data = {
      token: token.id,
      email
    };
    let response = await fetch("/charge", {
      method: "POST",
      headers: {
        "Content-Type": "text/plain"
      },
      body: JSON.stringify(data)
    });
    console.log(response);
    if (response.ok)
      this.setState({
        complete: true
      });
  };;

      render() {
        if (this.state.complete) return <h1> Purchase Complete </h1>;
        return (
          <CheckOut>
            <CheckOutForm>
              <CheckOutFieldSet>
                <InputRow>
                  <Label htmlFor=""> Name </Label>
                  <Input
                    type="text"
                    placeholder="Jane Doe"
                    onChange={this.handleChange("name")}
                  />
                </InputRow>
                <InputRow>
                  <Label htmlFor=""> Email </Label>
                  <Input
                    type="email"
                    placeholder="jane@doe.com"
                    onChange={this.handleChange("email")}
                  />
                </InputRow>
                <InputRow last>
                  <Label htmlFor=""> Phone </Label>
                  <Input type="phone" placeholder="+48 999 000 999" />
                </InputRow>
              </CheckOutFieldSet>
              <CheckOutFieldSet>
                <CardElement />
              </CheckOutFieldSet>
            </CheckOutForm>
            <ButtonCheckOut onClick={this.submit}> Send </ButtonCheckOut>
          </CheckOut>
        );
      }
    }

    export default injectStripe(CheckoutForm);

回复电子邮件存在,但 namecard 对象中

card: {id: "card_1", object: "card", 
address_city: null, 
address_country: null, 
address_line1: null, …}
created: 1546375333
email: "emial"
id: "tok_1Dnu4wj"
livemode: false
object: "token"
type: "card"
used: false
__proto__: Objec

名字

card:{
    last4: "4242"
    metadata: {}
    name: "Name"
}

后台

app.post("/charge", (req, res) => {
console.log(req.body)
//{"token":"tok_1DnuwhFw7kwjoel1NsD2Qd1r","email":"lll"}
stripe.charges.create({
    amount: 4000,
    currency: "usd",
    description: req.body.email,
    source: req.body.token
}).then(
    status => {
        res.json({
            status
        })
        // isValid = status.ok

    }
).catch(err => res.send(err))

let mail = req.body.email
console.log(mail)
//undefined

我知道console.log(req.body) 会给我令牌ID,但是如何发送更多的东西,比如电子邮件地址? 多一个?我刚刚在createToken 上收集的名字怎么可能?我包含在令牌中吗?

问候

【问题讨论】:

  • “发送更多信息,例如电子邮件或地址”是什么意思?您是否不仅要发送 fetch 请求正文 body: token.id 中的令牌 ID 吗?
  • 是的,我想发送更多数据
  • 那么你可能想要序列化你的数据。正如下面有人回答的那样,有一个函数JSON.stringify(data) 可以让你这样做。
  • 请看看我在获取部分和后端编辑了我的问题以记录数据。我越来越不确定
  • 您已设置'Content-Type': 'text/plain'。它必须是'application/json'。我还编辑了我的答案。

标签: node.js reactjs


【解决方案1】:

您可以在正文中发送一个对象,只需使用body: JSON.stringify(data)。数据可以包含任何可序列化的内容。

另外,请确保您的请求标头中有 'Content-Type': 'application/json'

正如@Dez 所指出的,确保您的服务器能够解析带有 JSON 有效负载的传入请求。对于express,您可以使用body-parser 中间件。

【讨论】:

  • UnhandledPromiseRejectionWarning:错误:发送后无法设置标头。
  • 请看一下后端,我编辑了这个以反映我得到的东西
  • 除了你已经指出的,OP 应该在 Node 服务器中设置这一行:app.use(bodyParser.json()); 以便能够接受 JSON 数据请求。
  • @Damian,不知道你为什么会收到这个错误,你的“BACKEND”sn-p 显示不够。我建议你看看here,看看是否有帮助,或者提供更多背景信息。
  • 它是bodyParser,但我在想为什么Stripe sn-p没有json而是文本作为bodyParser
猜你喜欢
  • 2023-03-30
  • 2023-03-11
  • 1970-01-01
  • 2016-01-17
  • 2017-08-08
  • 1970-01-01
  • 2020-05-30
  • 2020-12-24
  • 2020-05-06
相关资源
最近更新 更多