Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

node.js - How to properly make a GET request with redux and express.js

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...