反应,将数据发送到req.body中的后端,不能使用req.body形式的字段

时间:2019-01-01 20:51:06

标签: node.js reactjs

我正在构建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);

存在回复电子邮件,但名称card对象中

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"
}

BACKEND

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上收集的名字怎么可能?我包含在令牌中吗?

致谢

1 个答案:

答案 0 :(得分:2)

您可以使用body: JSON.stringify(data)体内发送对象。数据可以包含任何可序列化的内容。

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

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