Reactjs 我需要做什么才能在api中接收表单数据?
您好我在保存采购订单时遇到问题我无法接收表单数据我的代码如下:Reactjs 我需要做什么才能在api中接收表单数据?,reactjs,mongodb,api,next.js,react-forms,Reactjs,Mongodb,Api,Next.js,React Forms,您好我在保存采购订单时遇到问题我无法接收表单数据我的代码如下: 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
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;
我的常量不是接收表单数据,只是为了明确我正确接收的用户和产品数据。最大的问题是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);
我检查了您的CodeSandbox,但它失败了,因为您尝试在
api/checkout2
中获取undefined属性:
const{paymentData}=req.body;
在Cart.js中有这个
const handleCheckout=async(e)=>{
e、 预防默认值();
试一试{
设置加载(真);
常量url=`${baseUrl}/api/checkout2`;
const token=cookie.get(“token”);
const{电话、电子邮件、地址}=订单;
const payload={电话、电子邮件、地址};
const headers={headers:{Authorization:token}};
wait axios.post(url、有效负载、标题);//body对象中不存在paymentData
setOrder(初始订单);
设置成功(true);
}捕获(错误){
catchErrors(错误、窗口、警报);
console.log(订单)
}最后{
设置加载(假);
}
}
您正在api/Checkout2
objectpaymentData
有两种解决方案:
1.
您需要使用keypaymentData
和valuepayload
Cart.js
const handleCheckout=async(e)=>{
e、 预防默认值();
试一试{
设置加载(真);
常量url=`${baseUrl}/api/checkout2`;
const token=cookie.get(“token”);
const{电话、电子邮件、地址}=订单;
const payload={电话、电子邮件、地址};
const headers={headers:{Authorization:token}};
wait axios.post(url,{paymentData:payload},headers);
setOrder(初始订单);
设置成功(true);
}捕获(错误){
catchErrors(错误、窗口、警报);
console.log(订单)
}最后{
设置加载(假);
}
}
在api/checkout2中无需更改
2.
在Cart.js中无需更改
在api/checkout2的中:
改变这个
const { paymentData } = req.body;
借
您是否在express项目中添加了body parser库npm?不,确实可以,我会尝试,但我需要帮助,我是否应该安装npm安装body parser并在签出时导入它?我不使用express,我正在使用next.jsPlease,您能给代码沙盒测试它吗?非常感谢,多亏了你的帮助,我才能完成我的项目
const { paymentData } = req.body;
const {phone, email, address} = req.body;