【发布时间】:2020-04-29 13:47:38
【问题描述】:
我是前端技术的新手。我的要求是对外部服务器进行后期调用。我开始创建 react 应用程序并使用 axios 进行调用,但由于 CORS,我被拒绝访问。 stackoverflow 上的一些帖子提到我需要一个代理服务器来克服这个问题。因此,我也在项目中添加了一个快速部分。下面是我的反应和表达代码。
反应:
import React, { Component } from "react";
class App extends Component {
state = { posts: null };
componentDidMount() {
fetch("/posts")
.then(res => {
console.log(res);
return res;
})
.then(posts => this.setState({ posts: posts }));
}
render() {
return (
<div className="App">
<h1>Users</h1>
{this.state.posts}
</div>
);
}
}
export default App;
快递:
var express = require("express");
var router = express.Router();
const axios = require("axios");
router.get("/", function(req, res, next) {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => res.json(response.data))
.catch(err => next(err));
});
module.exports = router;
当我加载 React 应用程序时,我收到以下错误:
Error: Objects are not valid as a React child (found: [object Response]). If you meant to render a collection of children, use an array instead.
【问题讨论】:
-
这个
this.state.posts的值是多少。它需要是有效的 React 孩子。如果不是,您需要将它们转换为有效的孩子。阅读更多 objects-are-not-valid-as-a-react-child-if-you-meant-to-render-a-collection-of-c 和 objects-are-not-valid-as-a-react-child。您可能试图直接显示一个不可能的对象