Question

nextjs fetch data from backend

Posted August 25, 2021 126 views
Next.js

im using nexjs along with redux and im trying to fetch data from backend api which is running on port 5000. and my nextjs app on port 3000.

i tried module rewrite but its not working.

productActions.js:

import axios from 'axios'

export const listProducts = () => async (dispatch) => {
    try {
        dispatch({ type: 'PRODUCT_LIST_REQUEST' })

        const { data } = await axios.get('/api/products')

        dispatch({
            type: 'PRODUCT_LIST_SUCCESS',
            payload: data
        })
    } catch (error) {
        dispatch({
            type: 'PRODUCT_LIST_FAIL',
            payload: error.response && error.response.data.message
                ? error.response.data.message : error.message
        })
    }
}

next.config.js:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/products',
        destination: 'http://localhost:5000/api/products',
      },
    ]
  },
}

Submit an answer

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!