简体   繁体   中英

react cannot GET from express.js

I tried to connect my react.js front end with my express.js server in the backend, but I got this error.

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Here is the code

I have written this line of code inside package.json for the react app to allow access to the express app port

"proxy": "http://localhost:3001",

This is the express.js code I have written to respond for the GET request

const express = require('express');
const app = express();
const port = 3001;

app.set("view engine", "ejs");

app.get('/', (req, res) => {
    res.json({"message": "Hello World"});
});

app.listen(port, () => console.log(`The express server is listening at port ${port}...`));

And this is the react code

import React, { useState, useEffect } from "react";

function App() {
  const [response, setResponse] = useState("initial state");

  useEffect(() => {
    fetch("/").then(res => {
      if (res.ok) {
        return res.json();
      }
    }).then(responseData => setResponse(responseData));
  }, []);

  return (
    <div className="App">
      <h1>{response}</h1>
    </div>
  );
}

export default App;

I solved this problem by deleting the package-lock.json and node_modules files. Then I have reset the app by the command

npm install

Finally, I changed the routing to "/api" in both react.js and express.js apps to make it distinct from the root route of the react app.

the express code

const express = require('express');
const app = express();
const port = 3001;

app.set("view engine", "ejs");

app.get('/api', (req, res) => {
    res.json({message: "Hello World"});
});

app.listen(port, () => console.log(`The express server is listening at port ${port}...`));

the react code

import React, { useState, useEffect } from "react";

function App() {
  const [response, setResponse] = useState("initial state");

  useEffect(() => {
    fetch("/api").then(res => {
      if (res.ok) {
        return res.json();
      }
    }).then(responseData => setResponse(responseData.message));
  }, []);

  return (
    <div className="App">
      <h1>{response}</h1>
    </div>
  );
}

export default App;

I was stuck like you, I solved the problem when I restart react server you made a change to package.json through insert

( "proxy":"http://localhost:3001" )

so you should restart react to let react know your edition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM