[英]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.