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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…