亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的 React-Express 應用程序無法從 express 后端獲取和顯示數據?

為什么我的 React-Express 應用程序無法從 express 后端獲取和顯示數據?

米琪卡哇伊 2022-10-08 15:37:39
我的文件夾結構如下所示:server.js 里面的代碼:const express = require('express');const app = express();const port = process.env.PORT || 5000;// console.log that your server is up and runningapp.listen(port, () => console.log(`Listening on port ${port}`));// create a GET routeapp.get('/express_backend', (req, res) => {  res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });});App.js 內的代碼(位于客戶端文件夾中):import React, { Component } from 'react';import logo from './logo.svg';import './App.css';class App extends Component {state = {    data: null  };  componentDidMount() {      // Call our fetch function below once the component mounts    this.callBackendAPI().then(res => this.setState({ data: res.express })).catch(err => console.log(err));  }    // Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js  callBackendAPI = async () => {    const response = await fetch('/express_backend');    const body = await response.json();    if (response.status !== 200) {      throw Error(body.message)     }    return body;  };  render() {    return (      <div className="App">        <header className="App-header">          <img src={logo} className="App-logo" alt="logo" />          <h1 className="App-title">Welcome to React</h1>        </header>        <p className="App-intro">{this.state.data}</p>      </div>    );  }}export default App;包.json:{  "name": "dtdc-inside",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "author": "",  "license": "ISC",  "dependencies": {    "express": "^4.17.1"  },  "proxy": "http://localhost:5000/"}我已經運行“node server.js”沒有錯誤。cd 到客戶端目錄并運行“npm start”也沒有錯誤。但是,來自 server.js 的數據不會顯示在瀏覽器中。我需要幫助來理解為什么會這樣。感謝您的關注并原諒我糟糕的英語。
查看完整描述

2 回答

?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

Server.js 文件需要對服務器進行一些正確的更改


const express = require('express');

const app = express();

const port = process.env.PORT || 5000;


//Optional: add this line to parse incoming data. In case you want to accept data

app.use(express.json());


// create a GET route

app.get('/express_backend', (req, res) => {


  //generate output in `json` format rather than `send`.

  res.json({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });

});


//execute your server after writing all logic.

// console.log that your server is up and running

app.listen(port, () => console.log(`Listening on port ${port}`));


查看完整回答
反對 回復 2022-10-08
?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

感謝您的關注。隨著文件夾結構的變化(在根目錄中創建一個名為“backend”的新文件夾,然后將文件“server.js”移動到該文件夾中),代碼現在可以工作了。謝謝 -



查看完整回答
反對 回復 2022-10-08
  • 2 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號