我遇到以下代码。我在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);
},
上面的控制台日志:
控制器的片段:
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));
},
控制台日志结果: