【发布时间】: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);
回复电子邮件存在,但 name 在 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 上收集的名字怎么可能?我包含在令牌中吗?
问候
【问题讨论】:
-
“发送更多信息,例如电子邮件或地址”是什么意思?您是否不仅要发送 fetch 请求正文
body: token.id中的令牌 ID 吗? -
是的,我想发送更多数据
-
那么你可能想要序列化你的数据。正如下面有人回答的那样,有一个函数
JSON.stringify(data)可以让你这样做。 -
请看看我在获取部分和后端编辑了我的问题以记录数据。我越来越不确定
-
您已设置
'Content-Type': 'text/plain'。它必须是'application/json'。我还编辑了我的答案。