我正在构建 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"
}
后端
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
?我包含在令牌中吗?
问候