0

您好我在保存采购订单时遇到问题我无法接收表单数据我的代码如下:

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, email, 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;

现在这是我的结帐API:

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

我的常量没有接收表单数据,只是为了明确我正确接收的用户和产品数据。最大的问题是 paymentData 常量没有接收到handleCheckout函数中来自表单的内容

最后是我的订单模型,

// Order Model
import mongoose from 'mongoose';
import Product from './Product';

const { ObjectId, String, Number } = mongoose.Schema.Types;

const OrderSchema = new mongoose.Schema({
    user: {
        type: ObjectId,
        ref: "User"
    },
    products: [
        {
            quantity: {
                type: Number,
                default: 1
            },
            product: {
                type: ObjectId,
                ref: Product
            }
        }
    ],
    email: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    address: {
        type: String,
        required: true
    },
    total: {
        type: Number,
        required: true
    },
    status: {
        type: String,
        required: true,
        default: 'pending',
        enum: ["pending", "delivered"]
    }
},{
    timestamps: true
});

export default mongoose.models.Order || mongoose.model("Order", OrderSchema);
4

1 回答 1

1

我检查了您的 CodeSandbox 并且它失败了,因为您在执行此操作时试图获取 undefined in 的属性api/checkout2

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, email, 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, email, address} = order;
            const payload = {phone, email, address};
            const headers = {headers: {Authorization: token}};
            await axios.post(url, {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, email, address} = req.body;
于 2020-10-26T14:15:56.440 回答