简体   繁体   English

反应无法从 express.js 获取

[英]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.我尝试将我的 react.js 前端与后端的 express.js 服务器连接起来,但出现此错误。

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我在 package.json 中为 react 应用程序编写了这行代码,以允许访问 express 应用程序端口

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

This is the express.js code I have written to respond for the GET request这是我为响应 GET 请求而编写的 express.js 代码

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.我通过删除 package-lock.json 和 node_modules 文件解决了这个问题。 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.最后,我在 react.js 和 express.js 应用程序中将路由更改为“/api”,使其与 react 应用程序的根路由不同。

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我和你一样卡住了,当我重新启动反应服务器时,我解决了问题,你通过插入对 package.json 进行了更改

( "proxy":"http://localhost:3001" ) (“代理”:“http://localhost:3001”)

so you should restart react to let react know your edition所以你应该重新启动 react 让 react 知道你的版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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