【发布时间】:2020-12-26 06:48:27
【问题描述】:
我正在尝试创建一个 MERN 应用,同时使用 Axios 向后端发送请求,但我无法获取要在页面上呈现的数据。
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
export default class City extends Component {
constructor(props){
super(props);
this.state = {
selected_city: {
_id: "",
name: "",
country: ""
}
};
}
//Retrieves the requested city from the back-end to update the page's state.
componentDidMount(){
let city_name = this.props.match.params.name
axios.get('http://localhost:4000/city/' + city_name)
.then(response => {
console.log("Response: " + response);
console.log("Data: " + response.data);
console.log("String version: " + JSON.stringify(response.data));
console.log("Name: " + response.data.name);
this.setState({selected_city: response.data});
})
.catch(function(error){
console.log(error);
})
}
render() {
return (
<div className='text-center'>
<p>Name: {this.state.selected_city.name}</p>
<p>Description: {this.state.selected_city.country}</p>
</div>
)
}
}
用户应在主登录页面(例如伦敦)输入城市名称,然后登录到一个带有类似localhost:3000/city/<city-name> 的 URL 的页面,其中仅包含一些关于它的详细信息。
问题是,数据 显示在控制台中,如下所示:
Response: [object Object]
Data: [object Object]
String version: [{"_id":"5f5637ecf06f63e92b39e71d","name":"London","country":"United Kingdom"}]
如果我使用 Postman 查询端点,我也会得到预期的 JSON 响应。
编辑:我在 Axios GET 中添加了一个虚拟变量,如下所示:
axios.get('http://localhost:4000/city/' + city_name)
.then(response => {
console.log("Response: " + response);
var dummy_city = {"_id": "1215144156", "name": "London", "country": "United Kingdom"};
this.setState({
selected_city._id: dummy_city._id,
selected_city.name: dummy_city.name,
selected_city.country: dummy_city.country
//this.setState({selected_city: response.data});
})
.catch(function(error){
console.log(error);
})
...并且显示了虚拟数据,但是我仍然无法从 GET 响应中访问数据。我做错了什么?
【问题讨论】:
标签: node.js reactjs mongodb express axios