服务器发送html页面数据而不是实际数据?

时间:2019-06-25 22:24:56

标签: javascript node.js reactjs cors

我有一个React应用和一个node.js后端。在我的react组件中,我正在获取一些数据,但是服务器改为发送html页面。它在屏幕上显示原始html。

后端(server.js):

app.route("/a").get((req, res)=>{
    console.log("hello world");
    res.send("hello world")
})

frontend(app.js => component)

class App extends React.Component{
    state = {
        res: null
    }
    componentDidMount(){
        fetch("/a")
            .then(res=> res.text())
            .then(res=>this.setState({
                res
            }))
    }
    render(){
        return(
            <div>   
                <h1>yay</h1>
                <p>{ this.state.res }</p>
            </div>
        )
    }
}
export default App;

(index.js)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));


serviceWorker.unregister();

client package.json:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:5000",
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

昨天(我发布此问题的前一天),在关闭本地服务器之前,该应用程序运行正常。但是现在它表现得很怪异,当我打开客户端的package.json时,我发现proxy属性丢失了(我不知道是否意外删除了该属性),我认为我需要提及它假设有东西删除了它。 预先谢谢你。

html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

首先,尝试在server.js的其余部分中找到API的端口,然后将fetch("/a")更新为真实的API URL fetch("http://localhost:port/a"),之后,您必须允许来自react App的访问通过添加cors中间件将其添加到此端点:

  1. 安装用于快递的cors中间件软件包:$ npm install -s cors
  2. server.js中使用中间件
    1. 导入cors中间件var cors = require("cors");
    2. 通过添加行app.use(cors());
    3. 来使用它
  3. 再次运行代码

享受

答案 1 :(得分:0)

认为您需要更改获取以指向API位置,这可能是:

"http://localhost:5000/a"

不是

"/a"

这将指向您的主Web服务器