问题描述
您好,我在保存采购订单时遇到问题,我无法接收表单数据,其代码如下:
printf("\e[1;1H\e[2J");
现在这是我的结帐API:
import React from 'react';
import { parseCookies } from 'nookies';
import axios from 'axios';
import cookie from 'js-cookie';
import { Segment,Divider,Form,Button } from 'semantic-ui-react';
import CartItemList from "../components/Cart/CartItemList"
import baseUrl from '../utils/baseUrl';
import catchErrors from '../utils/catchErrors';
import calculateCartTotal from '../utils/calculateCartTotal';
const INITIAL_ORDER = {
phone: "",email: "",address: ""
};
const Cart = ({ products,user }) => {
// console.log(products)
const [cartProducts,setCartProducts] = React.useState(products);
const [success,setSuccess] = React.useState(false);
const [loading,setLoading] = React.useState(false);
const [cartAmout,setCartAmaount] = React.useState(0);
const [order,setorder] = React.useState(INITIAL_ORDER);
const [isCartEmpty,setCartEmpty] = React.useState(false);
React.useEffect(() => {
const { cartTotal } = calculateCartTotal(products);
setCartAmaount(cartTotal);
setCartEmpty(products.length === 0)
},[products]);
const handleChanhe = e => {
// console.log(d.value)
const { name,value} = e.target;
if(name === 'media'){
setorder(prevstate => ({ ...prevstate,media: files[0]}))
setMediaPreview(window.URL.createObjectURL(files[0]));
} else {
setorder(prevstate => ({ ...prevstate,[name]: value }));
}
console.log(order);
}
const handleRemoveFromCart = async (productId) => {
const url = `${baseUrl}/api/cart`;
const token = cookie.get("token");
const payload = {
params: {productId},headers: {Authorization: token}
};
const response = await axios.delete(url,payload);
setCartProducts(response.data);
}
const handleCheckout = async (e) => {
e.preventDefault();
try {
setLoading(true);
const url = `${baseUrl}/api/checkout2`;
const token = cookie.get("token");
const {phone,email,address} = order;
const payload = {phone,address};
const headers = {headers: {Authorization: token}};
await axios.post(url,payload,headers);
setorder(INITIAL_ORDER);
setSuccess(true);
} catch (error) {
catchErrors(error,window.alert);
console.log(order)
} finally {
setLoading(false);
}
}
return (
<div className="cart-area">
<Segment loading={loading}>
<CartItemList
handleRemoveFromCart={handleRemoveFromCart}
user={user}
products={cartProducts}
success={success}
/>
<React.Fragment>
<Divider />
<Segment clearing size="large" >
<strong>Sub total:</strong> ${cartAmout}
<Form success={success} onSubmit={handleCheckout}>
<Form.Input
fluid
icon="phone"
iconPosition="left"
label="Telefone"
placeholder="Tel"
name="phone"
type="text"
value={order.phone}
onChange={handleChanhe}
/>
<Form.Input
fluid
icon="envelope"
iconPosition="left"
label="Email"
placeholder="e-mail"
name="email"
type="email"
value={order.email}
onChange={handleChanhe}
/>
<Form.Input
fluid
icon="shipping"
iconPosition="left"
label="Rua e Numero"
placeholder="Rua e Nº"
name="address"
type="text"
value={order.address}
onChange={handleChanhe}
/>
<Form.Button
control={Button}
type="submit"
icon="cart"
color="green"
floated="right"
content="Checkout"
disabled={isCartEmpty || success}
/>
</Form>
</Segment>
</React.Fragment>
</Segment>
</div>
);
}
Cart.getinitialProps = async ctx => {
const { token } = parseCookies(ctx);
if (!token){
return { products: [] };
}
const url = `${baseUrl}/api/cart`;
const payload = { headers: {Authorization: token} };
const response = await axios.get(url,payload);
return { products: response.data };
}
export default Cart;
我的常量不是在接收表单数据,只是为了弄清我正确接收的用户和产品数据。最大的问题是paymentData常量未接收到handleCheckout函数中来自表单的内容
最后是我的订单模型,
import jwt from 'jsonwebtoken';
import Cart from '../../models/Cart';
import Order from '../../models/Order';
import calculateCartTotal from '../../utils/calculateCartTotal';
export default async (req,res) => {
const { paymentData } = req.body;
console.log(paymentData)
try {
const {userId} = jwt.verify(req.headers.authorization,process.env.JWT_SECRET);
const cart = await Cart.findOne({ user: userId }).populate({
path: "products.product",model: "Product"
});
const {cartTotal} = calculateCartTotal(cart.products);
await new Order({
user: userId,email: paymentData.email,address: paymentData.address,phone: paymentData.phone,total: cartTotal,products: cart.products
}).save();
await Cart.findOneAndUpdate(
{_id: cart._id},{$set: {products: []}}
)
res.status(200).send("Checkout successful!");
} catch (error) {
console.error(error);
res.status(500).send("Error proccessing charge");
}
}
解决方法
我检查了您的CodeSandbox并失败了,因为您尝试这样做时试图在api/checkout2
中获得undefined的属性:
const {paymentData} = req.body;
而您在Cart.js
const handleCheckout = async (e) => {
e.preventDefault();
try {
setLoading(true);
const url = `${baseUrl}/api/checkout2`;
const token = cookie.get("token");
const {phone,email,address} = order;
const payload = {phone,address};
const headers = {headers: {Authorization: token}};
await axios.post(url,payload,headers); //Not exists paymentData in body object
setOrder(INITIAL_ORDER);
setSuccess(true);
} catch (error) {
catchErrors(error,window.alert);
console.log(order)
} finally {
setLoading(false);
}
}
您正在api/Checkout2
对象paymentData
中等待
有2个解决方案:
1
您需要使用键paymentData
和值payload
创建新对象
Cart.js
const handleCheckout = async (e) => {
e.preventDefault();
try {
setLoading(true);
const url = `${baseUrl}/api/checkout2`;
const token = cookie.get("token");
const {phone,{paymentData: payload},headers);
setOrder(INITIAL_ORDER);
setSuccess(true);
} catch (error) {
catchErrors(error,window.alert);
console.log(order)
} finally {
setLoading(false);
}
}
api/checkout2
2
Cart.js
中没有任何变化
在api/checkout2
中:
更改此
const { paymentData } = req.body;
作者
const {phone,address} = req.body;