-2

I have a react app and a backend of node.js. In my react component i'm fetching some data but the server sends the html page instead. It shows raw html in the screen.

backend(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"
    ]
  }
}

Yesterday (the day before I posted this question), The app was working fine before I shut off the local servers. But now it acts weird and when I opened the package.json of client side, I noticed that proxy property is missing (I don't know if I removed it accidently), I think that I need to mention it assuming that something deleted it. Thank you in advance.

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>
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Eye Patch
  • 881
  • 4
  • 11
  • 23
  • it shows `

    hello world

    `?
    – Jamal Abo Jun 25 '19 at 22:33
  • No, it shows the `index.html` file as text in the page. The server, i think, isn't linked to this page and it doesn't render it. I am using server in port 5000 and react app in 3000. – Eye Patch Jun 25 '19 at 22:37
  • I don't see `index.html` in your code, nor dealing with `index.html`, or do you mean sending `index.html` of Reactjs? (`public/index.html`) – Jamal Abo Jun 25 '19 at 22:39
  • isn't it because your ports don't match? What happens if you point the browser at 5000? – Ben Gannaway Jun 25 '19 at 22:43
  • it shows just `hello world` to the page. – Eye Patch Jun 25 '19 at 22:44
  • show us a bit more of your express server. What express route returns the index.html that you keep getting? if none, then you're ajax is probably targeting the wrong server. In fact, it is targeting the wrong server. Use the correct port number. – Kevin B Jun 25 '19 at 22:45
  • In express server, there is only one route which is `/a` and I used `proxy` property in `package.json` to make the server as default, like `/a` instead of `http://localhost:5000` – Eye Patch Jun 25 '19 at 22:48

2 Answers2

1

First, try to locate your API's port in the rest of server.js, and then update the fetch("/a") to the real API URL fetch("http://localhost:port/a") after that you have to allow access from react App to this endpoint by adding cors middleware:

  1. Install the cors middleware package for express: $ npm install -s cors
  2. Use the middleware in your server.js
    1. Import cors midleware var cors = require("cors");
    2. Use it by adding the line app.use(cors());
  3. Run the code again

Enjoy

Tenma Kenzo
  • 354
  • 5
  • 9
0

Think you need to change your fetch to point at the API location, which is probably:

"http://localhost:5000/a"

not

"/a"

which will just point back to your main webserver

Ben Gannaway
  • 1,053
  • 1
  • 14
  • 28
  • It shows some errors `Access to fetch at 'http://localhost:5000/a' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I think that I can use `/a` because I am using `proxy` in `package.json` – Eye Patch Jun 25 '19 at 22:51
  • I'm not sure what proxy in package.json does. You can either use CORS plugin on your API: https://expressjs.com/en/resources/middleware/cors.html or move your API route onto your main server? – Ben Gannaway Jun 25 '19 at 22:54
  • Apparently, the problem is not from CORS, i tried the cors middleware and nothing changed. As I read in some tutorials, `proxy` in package.json solve the CORS problem. – Eye Patch Jun 25 '19 at 23:16