Node.js React,数据发送到req.body中的后端,can';t使用字段表单req.body

Node.js React,数据发送到req.body中的后端,can';t使用字段表单req.body,node.js,reactjs,Node.js,Reactjs,我正在构建React/Node/Stripe应用程序,基本设置工作正常,但当我想扩展我的应用程序以从输入表单收集电子邮件地址并将其发送到body-to-Node后端以使用它创建客户或发送电子邮件时。我在console.log中看到req.body电子邮件中存在,但我可以获取此字段 反应 电子邮件已收集 import React, { Component } from "react"; import { CardElement, injectStripe } from "react-stripe

我正在构建React/Node/Stripe应用程序,基本设置工作正常,但当我想扩展我的应用程序以从输入表单收集电子邮件地址并将其发送到body-to-Node后端以使用它创建客户或发送电子邮件时。我在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);
名字

后端

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
上收集的名字怎么可能?我是包括在代币


关于

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

另外,确保在请求头中有
“Content-Type”:“application/json”


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

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

另外,确保在请求头中有
“Content-Type”:“application/json”



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

您所说的“发送更多邮件或地址”是什么意思?是否不仅要发送fetch请求正文中的令牌id
body:token.id
?是的,我要发送更多数据,然后您可能要序列化数据。正如下面有人回答的那样,有一个函数
JSON.stringify(data)
,允许您这样做。请看一看,我在fetch部分编辑了我的问题,并在后端编辑了日志数据。我无法定义您已设置的
'Content-Type':'text/plain'
。它需要是
'application/json'
。我还编辑了我的答案。你说的“发送更多邮件或地址”是什么意思?是否不仅要发送fetch请求正文中的令牌id
body:token.id
?是的,我要发送更多数据,然后您可能要序列化数据。正如下面有人回答的那样,有一个函数
JSON.stringify(data)
,允许您这样做。请看一看,我在fetch部分编辑了我的问题,并在后端编辑了日志数据。我无法定义您已设置的
'Content-Type':'text/plain'
。它需要是
'application/json'
。我还编辑了我的答案。UnhandledPromisejectionWarning:错误:发送邮件后无法设置邮件头。请查看我编辑此邮件的后端,以反映我得到的信息。除了您已经指出的,OP应该在节点服务器中设置以下行:
app.use(bodyParser.json())
以便能够接受JSON数据请求。@Damian,不确定为什么会出现此错误,您的“后端”代码段显示的内容不够。我建议你看一下,看看这是否有帮助,或者提供更多的上下文。它是bodyParser,但是我在想为什么Stripe snippet没有json,而是作为BodyParseRunHandledPromisejectionWarning的文本。错误:发送后无法设置标题。请查看我编辑的后端,以反映我得到的内容。除了您已经指出的,OP应该在节点服务器中设置以下行:
app.use(bodyParser.json())
以便能够接受JSON数据请求。@Damian,不确定为什么会出现此错误,您的“后端”代码段显示的内容不够。我建议你们看一看,看看这是否有帮助,或者提供更多的上下文。这是bodyParser,但我在想为什么Stripe代码段并没有json,而是文本作为bodyParser
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