-1

I am having a problem with making a GET request with redux and express.js. I need to pass some date to the backend which then it will query some report on sales. Now i have used postman and it works and it gives me the data i need, but when i do the redux part and trying to display that data, it says "Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body" . Now i get that i need to remove the body and add the query to the url, but what should i do? where should i do it? im confused if i need to modify both front end and back end in order to get the query. Can anyone help me on solving this? This is what i did so far:

Front-end (Redux) [EDITED]

export const getCustomProfitReport = (startDate, endDate) => (dispatch) => {
    dispatch(customProfitReportLoading(true))

    const bearer = 'Bearer ' + localStorage.getItem('token')

    let params = {
        "param1": startDate,
        "param2": endDate
    }

    let query = Object.keys(params)
                .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
                .join('&')

    return fetch(baseUrl + 'custom-profit-report?' + query, {
        method: 'GET',
        headers: {
            'Authorization': bearer
        }
    })
    .then(response => {
        if (response.ok) {
            return response
        }
        else {
            var error = new Error('Error ' + response.status + ': ' + response.statusText);
            error.response = response;
            throw error;
        }
    },
    error => {
        var errmess = new Error(error.message);
        throw errmess;
    })
    .then(response => response.json())
    .then(sales => dispatch(addCustomProfitReport(sales)))
    .catch(error => dispatch(customProfitReportFailed(error.message)))
}

This is the backend (express)

const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
var authenticate = require('../authenticate')
const cors = require('./cors')

const Sales = require('../models/sales')

const customProfitRouter = express.Router()

customProfitRouter.use(bodyParser.json())

customProfitRouter.route('/')
.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200) })
.get(cors.cors, authenticate.verifyUser, authenticate.verifyAdmin, (req,res,next) => {
    let start = req.params.startDate
    let end = req.params.endDate

    Sales.find({ 
        "createdAt": 
        { 
            $gte: start, 
            $lte: end 
        } 
    })
    .populate('property')
    .populate('fee')
    .then((sales) => {
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json')
        res.json(sales)
    }, (err) => next(err))
    .catch((err) => next(err))
})

module.exports = customProfitRouter
arkanoid
  • 19
  • 1
  • 4

2 Answers2

0

EDIT for updated question

You should change your client code from:

let params = {
    "param1": startDate,
    "param2": endDate
}

to:

let params = {
    startDate: startDate,
    endDate: endDate
}

or the shorter version:

let params = {
    startDate,
    endDate
}

You can't send a fetch request of type GET that has a body.

See this answer on how to use fetch with query params.
Also, on your express server side - take the parameters from req.params insted of req.body - check the express Request documentation here

You can read more about the issue on the "fetch" github issues page.

Nimrod Shory
  • 2,475
  • 2
  • 19
  • 25
  • thank you for replying. Now i modified the redux part as i watched some example on the post you linked. Look above as i edited the post. The backend i substituted as you told me. What is missing? Am i in the right direction? how two params will be taken from the backend, like which one is which? – arkanoid Dec 30 '20 at 15:51
0

The solution is modify some lines in the backend so substitute start and end with :

    let start = req.query.param1
    let end = req.query.param2  

its a little modification and it works.. Hopefully it will help somebody!

arkanoid
  • 19
  • 1
  • 4