【问题标题】:Getting Error 400 (Bad Request) When I Submit Data in MERN当我在 MERN 中提交数据时出现错误 400(错误请求)
【发布时间】:2020-12-30 06:19:55
【问题描述】:

我正在尝试将产品保存在我的 MERN 项目中。当我尝试提交数据时,我收到此消息 http://localhost:8000/api/product/create/5f4e7732333b2b21ec06a9f5 400(错误请求) 当我检查网络中的响应时,它给出了 {"error":""} 它没有给出错误信息。请检查我的代码并指导我。

AddProduct.js

import React, {useState, useEffect} from 'react';
import Layout from '../core/Layout';
import {isAuthenticated} from '../auth';
import {createProduct, getCategories} from './apiAdmin';

const AddProduct = () => {

const [values, setValues] = useState({
    name: '',
    description: '',
    price: '',
    categories: [],
    category: '',
    shipping: '',
    quantity: '',
    photo: '',
    loading: false,
    error: '',
    createProduct: '',
    redirectToProfile: false,
    formData: ''
});

const {user, token} = isAuthenticated();

const {
    name,
    description,
    price,
    categories,
    category,
    shipping,
    quantity,
    loading,
    error,
    createProducts,
    redirectToProfile,
    formData
} = values;

const init = () => {
    getCategories().then(data => {
        if(data.error){
            setValues({...values, error: data.error})
        } else{
            setValues({...values, categories: data.data, formData: new FormData()});
        }
    });
};

useEffect(() => {
    init();
}, []);

const handelChnage = name => event => {
    const value = name === 'photo' ? event.target.files[0] : event.target.value
    formData.set(name, value)
    setValues({...values, [name]: value})
};

const clickSubmit = (event) => {
    event.preventDefault();
    setValues({...values, error: '', loading: true});

    createProduct(user._id, token, formData).then(data =>{
        if(data.error){
            setValues({...values, error: data.error})
        } else{
            setValues({
                ...values, 
                name: '',
                description: '',
                photo: '',
                price: '',
                quantity: '',
                loading: false,
                createProduct: data.name
            });
        }
    });

};

const newPostForm = () => (
    <form className="mb-3" onSubmit={clickSubmit}>
        <h4>Post Photo</h4>
        <div className="form-group">
            <label className="form-group">
                <input onChange={handelChnage('photo')} type="file" name="photo" accept="image/*" />
            </label>
        </div>
        <div className="form-group">
            <label className="text-muted">Name</label>
            <input onChange={handelChnage('name')} type="text" className="form-control" value={name} />
        </div>
        <div className="form-group">
            <label className="text-muted">Description</label>
            <textarea onChange={handelChnage('description')} className="form-control" value={description} />
        </div>
        <div className="form-group">
            <label className="text-muted">Price</label>
            <input onChange={handelChnage('price')} type="number" className="form-control" value={price} />
        </div>
        <div className="form-group">
            <label className="text-muted">Category</label>
            <select onChange={handelChnage('category')} className="form-control" >
                    <option>Please Select</option>
                    {categories && categories.map((c,i) => (
                        <option key={i} value="{c._id}">
                            {c.name}
                        </option>
                    ))}
            </select>
        </div>
        <div className="form-group">
            <label className="text-muted">Shipping</label>
            <select onChange={handelChnage('shipping')} className="form-control" >
                <option>Please Select</option>
                <option value="0">No</option>
                <option value="1">Yes</option>
            </select>
        </div>
        <div className="form-group">
            <label className="text-muted">Quantity</label>
            <input onChange={handelChnage('quantity')} type="number" className="form-control" value={quantity} />
        </div>
        <button className="btn btn-outline-primary">Create Category</button>
    </form>
);

const showError = () =>{
    return(
        <div className="alert alert-danger" style={{display: error ? '' : 'none'}}>
            {error}
        </div>
    );
};

const showSuccess = () =>{
    return(
        <div className="alert alert-info" style={{display: createProducts ? '' : 'none'}}>
            <h2>product is created!</h2>
        </div>
    );
};

const showLoading = () =>
    loading && (
        <div className="alert alert-info">
            <h2>Loading...</h2>
        </div>
    );

return(
    <Layout title="Add New Product" description={`Welcome ${user.name}!`} className="container-fluid" >        
        <div className="row">
            <div className="col-8 offset-md-2">
                {showLoading()}
                {showSuccess()}
                {showError()}
                {newPostForm()}
            </div>
        </div>
    </Layout>
    );

    };

  export default AddProduct;

apiAdmin.js

 export const createProduct =  (userId, token, product) =>{
//console.log(name, photo, description, price, category, shipping, quantity);
const url = `http://localhost:8000/api/product/create/${userId}`;
//console.log(url);
return fetch(url, {
    method: "POST",
    headers:{
        Accept: 'application/json',
        Authorization : `Bearer ${token}`
    },
    body: product
})
.then(response => {
    return response.json();
})
.catch(err =>{
    console.log(err);
});
};

请帮帮我

提前致谢

【问题讨论】:

    标签: node.js reactjs mongodb


    【解决方案1】:
    const [values, setValues] = useState({
        name: '',
        description: '',
        price: '',
        categories: [],
        category: '',
        shipping: '',
        quantity: '',
        photo: '',
        loading: false,
        error: '',
        createdProduct: '', -> edit 
        redirectToProfile: false,
        formData: ''
    });
    
    const {user, token} = isAuthenticated();
    
    const {
        name,
        description,
        price,
        categories,
        category,
        shipping,
        quantity,
        loading,
        error,
        createdProduct, -> edit
        redirectToProfile,
        formData
    } = values;
    

    【讨论】:

    • 您能否在此代码中添加解释,以帮助人们了解您所做的更改以及如何解决问题。
    • createProduct(user._id, token, formData).then(data =>{ if(data.error){ setValues({...values, error: data.error}) } else{ setValues({ ...values, name: '', description: '', photo: '', price: '', quantity: '', loading: false, createdProduct: data.name --> edit }); }
    • 您的答案下方有一个edit 按钮。如果您想进行更改,或者,例如,为您的答案添加解释,这就是这样做的方法。
    • @NatanielRantetampang 感谢您的回答,但我的问题现在已经解决了......非常感谢
    猜你喜欢
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2012-08-06
    • 2019-07-17
    • 1970-01-01
    相关资源
    最近更新 更多