REQ.BODY在GET调用中作为空传递

时间:2018-09-23 05:45:52

标签: mysql reactjs sequelize.js

我遇到以下代码。我在js中创建一个对象,然后执行API调用,将该对象传递给控制器​​。该对象填充在js组件和API组件中,但到达控制器时为空。我已经验证我有app.use(bodyParser.urlencoded({扩展名:true}));建议将其编码在我的服务器代码中,以解决其他类似问题。

js / API调用片段:

getGeoLocation = () => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            let latLng = {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
                name: "current location",
                details: false,
                detailsText: null,
                markerIcon: currentLocation
            };
            let searchData = {
                currentLat: latLng.lat,
                currentLng: latLng.lng,
                dist: this.state.dist,
                limit: this.state.limit
            };
            console.log("in JS component:");
            console.log(searchData);

            API.getLocations(searchData)
                .then(res =>
                    this.setState({ markers: res.data }),
                    console.log("markers: "),
                    console.log(this.state.markers),
                    this.setState(prevState => ({
                        currentLatLng: latLng,
                        markers: [latLng, ...prevState.markers]
                    }))
                )
                .catch(err => console.log(err));
            console.log(this.state.markers)
        }); 

API片段:

import axios from "axios";

export default {
  // Gets all locations
  getLocations: function(searchData) {
    console.log("in API:");
    console.log(searchData);
    return axios.get("/api/locations/", searchData);
  },

上面的控制台日志:

enter image description here

控制器的片段:

module.exports = {
findAll: function (req, res) {
    console.log("req.body in controller:");
    console.log(req.body);
    db.Locations
        .findAll({
            attributes: { include: [[sequelize.literal("(3959 * acos(cos(radians(" + req.body.currentLat + ")) * cos(radians(lat)) * cos(radians(lng) - radians(" + req.body.currentLng + ")) + sin(radians(" + req.body.currentLat + ")) * sin(radians(lat))))"), 'distance']] },
            having:
                sequelize.where(sequelize.col('distance'),
                    { [Op.lte]: req.body.dist }
                ),
            order: sequelize.col('distance'),
            limit: req.body.limit
        })
        .then(dbModel =>
            res.json(dbModel))
        .catch(err => res.status(422).json(err));
},

控制台日志结果:

enter image description here

1 个答案:

答案 0 :(得分:4)

第二个axios.get参数是一个配置对象,而不是请求正文,请参见herethis github问题。
尽管GET请求规范并未明确禁止发送带有GET请求的请求正文,但应避免使用它,因为有许多框架和库会忽略它,因此您应该在查询字符串,而不是在请求正文中。