简体   繁体   中英

Nodejs MongoDB - add new entry Post()

so trying to post new entry into MongoDB. but getting this error in Redux Product validation failed: name: Path 'name' is required., description: Path 'description' is required.

nodejs version: 14.9.0 and Atlas mongodb.

frontEnd addProduct.js page:

import { createProduct } from '../redux/actions/productActions'

const [name, setName] = useState('')
const [description, setDescription] = useState('')


const createProductHandler = (e) => {
    e.preventDefault()
    dispatch(createProduct({
        name,
        description
    }))
}

 const nameHandler = (e) => {
    setName(e.target.value)
}

const descriptionHandler = (e) => {
    setDescription(e.target.value)
}

return (
  <input type='text' onChange={nameHandler} />
  <input type='text' onChange={descriptionHandler} />
  <input type="submit" value='submit' onClick={createProductHandler} />
)

productController:

const createdProduct = asyncHandler(async (req, res) => {
  const mongoProduct = async (data) => {
    return new Product({
        name: data.name,
        description: data.description
    })
  }

 const product = await mongoProduct(req.body)

 const createdProduct = await product.save()

 res.status(201).json(createdProduct)
})

productActions:

export const createProduct = () => async (dispatch, getState) => {
try {
    dispatch({
        type: 'PRODUCT_CREATE_REQUEST',
    })

    const {
        userLogin: {userInfo},
    } = getState()

    const config = {
        headers: {
            Authorization: `Bearer ${userInfo.token}`,
        },
    }

    const { data } =  await axios.post(`/api/products`, {}, config)

    dispatch({
        type: 'PRODUCT_CREATE_SUCCESS',
        payload: data
    })
} catch (error) {
    dispatch({
        type: 'PRODUCT_CREATE_FAIL',
        payload:
            error.response && error.response.data.message
                ? error.response.data.message
                : error.meessage,
    })
 }
} 

productReducers.js:

export const productCreateReducer = (state = {}, action) => {
switch (action.type) {
    case 'PRODUCT_CREATE_REQUEST':
        return {loading: true}
    case 'PRODUCT_CREATE_SUCCESS':
        return {loading: false, success: true, product: action.payload}
    case 'PRODUCT_CREATE_FAIL':
        return {loading: false, error: action.payload}
    default: 
        return state
 }
}

alternatively when i try to populate the database from post-man using this code in productController.js it works fine with sample data:

const createdProduct = asyncHandler(async (req, res) => {
 const product = new Product({
    name: 'Sample Name',
    description: 'Sample Description'
 })

 const createdProduct = await product.save()
 res.status(201).json(createdProduct)
})

plus im getting POST ipadress/api/products 500 (Internal Server Error) in console

You can config your axios api service config to separate file and use axios

const request = axios.create({
  // baseURL: 'https://mock-api.com',
  baseURL: BASE_URL ,
  timeout: 5000
})

request.interceptors.request.use(
  config => {
    // get token
    if (// check your token) {
      config.headers["Authorization"] = "Bearer ${your-token}"
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// Can also config axios response interceptors to handle API error

Your redux action

import axiosInstance from './your-axios-config-path'

export const createProduct = (product) => async (dispatch, _getState) => {
  try {
    dispatch({ type: 'PRODUCT_CREATE_REQUEST' })
    const response = await axiosInstance.post(`/api/products`, {...product})
    dispatch({
      type: 'PRODUCT_CREATE_SUCCESS',
      payload: response?.data ?? {}
    })
  } catch (error) {
    dispatch({
      type: 'PRODUCT_CREATE_FAIL',
      payload: // error message,
    })
  }
}

Alternatively, you can useRedux Toolkit , It much easier to setup store and using. It includes createAsyncThunk , RTK Query to handle side effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM