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() { this.componentDidMount(); 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使用访存访问快递
这里是错误日志,它的发生是因为请求中的主体为null,即响应带有空主体
import React,{Component} from'react';导入'../styles/App.css'; App类扩展了Component {Constructor(){super(); this.state = {产品:[]}; } componentDidMount(){...
发生的事情是您的代码没有等待调用结束。