![](/img/trans.png)
[英]How to configure a proxy like in CRA without create-react-app?
[英]Error fetch from react to express without CRA(create-react-app)
import React,{Component} from 'react';
import '../styles/App.css';
class App extends Component{
constructor() {
super();
this.state = {
products: []
};
}
componentDidMount() {
fetch('http://localhost:4000/products', {
method: 'GET',
mode: "no-cors",
headers: {"Content-Type": "application/json"}
}).then(res => {console.log(res);res.json()})
.then(products => this.setState({products}));
}
render() {
return (
<div>
<h1>Hello, react.js!!!</h1>
<ul>
{this.state.products.map(product => <li>{product.product_name}</li>)}
</ul>
</div>
);
}
}
export default App;
express.js 监听 4000 端口。这 express.js 部分
app.get("/products", (req, res) => {
conn.query('SELECT * FROM products', (err, result) => {
if(err) {throw err;}
console.log(result);
res.json(result);
});
});
如果我只是在地址栏中输入 http://localhost:4000/products ,那么我会得到一个 json 响应,但是在组件应用程序中 react.JS fetch 返回一个错误,因为响应包含一个空正文,这意味着地址不可用。 此错误与 CORS 有关,但我不知道如何修复它。
也许如果您知道如何为此使用和配置代理,那么我将非常感谢您的提示。
App.js 使用 fetch 访问 express
发生的事情是您的代码没有等待调用完成。
您可以使用async-await
功能。
此链接可能会有所帮助: https://www.valentinog.com/blog/await-react/
作为 OP 编辑和添加示例无法访问该链接。
尝试这个:
async componentDidMount() {
const response = await fetch('http://localhost:4000/products', {
method: 'GET',
mode: "no-cors",
headers: {"Content-Type": "application/json"}
});
const json = await response.json();
// Do stuff with json
console.log(json);
this.setState(json);
}
如此简单也可能有效,但请检查:
async componentDidMount() {
await fetch('http://localhost:4000/products', {
method: 'GET',
mode: "no-cors",
headers: {"Content-Type": "application/json"}
}).then(res => {console.log(res);res.json()})
.then(products => this.setState({products}));
}
您还在您的快递项目中启用CORS
吗?
你不需要this.componentDidMount();
. 删除该行。 作为反应组件生命周期的一部分,它将自动执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.