【发布时间】:2016-11-16 00:32:28
【问题描述】:
我是新来的反应并使用 create-react-app 作为起点。我有一个返回 json 数据的 api。我使用端口 3000 上的节点服务器运行我的 api。
我还有默认的 create-react-app 设置,它使用端口 3000 启动应用程序。我想从我的 api 获取数据并在我的 react 应用程序中渲染它。我收到由于跨源请求而无法检索数据的错误。这通常在 webpack 中如何处理?
下面是我的代码,但我本质上想进行如下调用:NodeFetch('/api/jobs') 以访问在端口 3001 上运行的我的 api 返回的数据。
这是我的代码:
import React from 'react'
import NodeFetch from 'node-fetch'
class NodeFetchData extends React.Component {
constructor(props) {
super(props);
this.state = {
jobs: []
};
}
componentDidMount() {
NodeFetch('http://codepen.io/jobs.json')
.then(res => {
this.setState({ jobs:res.data.jobs });
});
}
render() {
return (
<div>
<ul>
{this.state.jobs.map(job =>
<li key={job.hashid}>{job.company_name}</li>
)}
</ul>
</div>
);
}
}
export default NodeFetchData;
【问题讨论】:
-
显示一些代码以提出建议
标签: node.js express webpack fetch