如何让我的 server.js 访问 redux 值?

How do I get my server.js to access redux values?

我有一个商店的结帐页面,其中包含一些输入,例如地址、名称等。我也想将购物车信息上传到 mongodb,但它不起作用。购物车信息来自 redux,使用 redux 的 useSelector,但我无法将该函数放入 server.js。有没有人有任何提示?我也提供了下面的架构。

Server.js

require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const connectDB = require('./config/db');
const productRoutes = require('./routes/productRoutes');
const CustomerInfo = require("./models/customerInfo");

connectDB();

const app = express();

app.use(express.json());

app.use('/api/products', productRoutes);

const PORT = process.env.PORT || 5000;

app.use(bodyParser.urlencoded({extended: true}));


//app.post

app.post ("/", function(req, res) {
    let newCustomerInfo = new CustomerInfo({
        fname: req.body.firstName,
        lname: req.body.lastName,
        email: req.body.email,
        phone: req.body.phoneNumber,
        address: req.body.address,
        city: req.body.city,
        district: req.body.district,
        section: req.body.section,
        confirmCode: req.body.confirmCode,
        comments: req.body.extraInfo,
        cartItems: req.body.cartcount
    });
    newCustomerInfo.save();
    res.redirect("/");
})

app.listen(PORT, () => console.log(`Server Running on port ${PORT}`))

CheckoutScreen.js

import './CheckoutScreen.css';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';

// Components
import CartItem from '../components/CartItem';


const CheckoutScreen = () => {

    const cart = useSelector(state => state.cart);
    const { cartItems } = cart;

    const getCartCount = () => {
        return cartItems.reduce((qty, item) => Number(item.qty) + qty, 0)
    };

    const getCartSubTotal = () => {
        return cartItems.reduce((price, item) => item.price * item.qty + price, 0)
    };
    return (
        <div className="checkoutscreen">
            <div className="checkout__left">
                <body>
                    <form className="checkout-form" method="post" action="/">
                        <label className="input">
                            <input type="text" name="firstName" required/>
                            <span className="placeholder">First Name</span>
                        </label>
                        <label className="input">
                            <input type="text" name="lastName" required/>
                            <span className="placeholder">Last Name</span>
                        </label>
                        <label className="input">
                            <input type="text" name="email" required/>
                            <span className="placeholder">Email</span>
                        </label>
                        <label className="input">
                            <input type="text" name="phoneNumber" required/>
                            <span className="placeholder">Phone Number</span>
                        </label>
                        <label className="input">
                            <input type="text" name="address" required/>
                            <span className="placeholder">Address</span>
                        </label>
                        <label className="input">
                            <input type="text" name="city" required/>
                            <span className="placeholder">City</span>
                        </label>
                        <label className="input">
                            <input type="text" name="district" required/>
                            <span className="placeholder">District</span>
                        </label>
                        <label className="input">
                            <input type="text" name="section" required/>
                            <span className="placeholder">Section</span>
                        </label>
                        <label className="input">
                            <input type="text" name="confirmCode" required/>
                            <span className="placeholder">Confirmation Code</span>
                        </label>
                        <label className="input">
                            <input type="text" name="extraInfo" required/>
                            <span className="placeholder">Details/Comments</span>
                        </label>
                        <p className="cartcount">{getCartCount()}</p>
                        <button>Submit</button>
                    </form>
                </body>
            </div>
            <div className ="checkout__right">
            <div className="checkout__info">
                    <p>Subtotal ({getCartCount()}) items</p>
                    <p>${getCartSubTotal().toFixed(2)}</p>
                </div>
            </div>
        </div>
    )
};



export default CheckoutScreen;

customerInfo.js

const mongoose = require("mongoose");

const customerInfoSchema = new mongoose.Schema ({
    fname: {
        type: String,
        required: true
    },
    lname: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    address: {
        type: String,
        required: true
    },
    city: {
        type: String,
        required: true
    },
    district: {
        type: String,
        required: true
    },
    section: {
        type: String,
        required: true
    },
    confirmCode: {
        type: String,
        required: true
    },
    comments: {
        type: String,
        required: false
    },
    cartItems: {
        type: Number,
        required: true
    }
});

const customerInfo = mongoose.model('Customer Info', customerInfoSchema);

module.exports = customerInfo;

您需要在 Server.js 中致电您的 API。要调用 API,您需要提交表单并通过表单 onSubmit 事件上的 handleSubmit 方法处理表单提交。在 handleSubmit 方法中,您需要调用结帐操作并传递购物车对象。 CheckoutAction 需要使用 redux-thunk 异步调用服务器 api (中间件的副作用)。一旦响应返回,您可以通过发送到 CheckoutReducer

return 状态

CheckoutScreen.js

import { Checkout } from '../action/checkoutAction'
const dispatch = useDispatch();

...........

const handleCheckout = e => {
  e.preventDefault();
  dispatch(Checkout({ type:'CHECKOUT', payload:cart }));
}

......

<form className="checkout-form" method="post" action="/" onSubmit={e => handleCheckout(e)}>

CheckoutAction.js

export const Checkout = data => async dispatch => {
  let response = await axios.post(server_api_url, data);

  dispatch({ type: 'checkout_success', payload:response.data}); //to checkout reducer
}