来自 React.js 应用程序的请求未命中 Node.js 后端端点

编程入门 行业动态 更新时间:2024-10-03 12:39:11

来自 React.js <a href=https://www.elefans.com/category/jswz/34/1771452.html style=应用程序的请求未命中 Node.js 后端端点"/>

来自 React.js 应用程序的请求未命中 Node.js 后端端点

我正在制作

React
node
申请。

Node
正在端口
3001
上运行。

var port = normalizePort(process.env.PORT || '3001'); //in bin/www

React
配置了代理并在端口 3000 上运行。

"proxy": "http://localhost:3001", //in package.json

Node

app.js
已为
/
定义路线。

app.use('/', indexRouter); //a path  with / goes to indexRouter

routes/index.js
将请求传递给控制器。

var express = require('express');
var router = express.Router();
let index = require('../controllers/index');

/* GET home page. */
router.get('/', index.index);

module.exports = router;

controllers/index.js
回复
json

exports.index = function(req, res, next) {
    console.log('index page'); //I DONT SEE THIS TRACE
    res.json({message: `some message` });
}

React
app.js
中,发送请求,等待响应

import React from "react";
import logo from './logo.svg';
import './App.css';

function App() {

  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    fetch("/")
      .then((res) => {
        console.log(`got response ${res}`)
        res.json()}
        )
      .then((data) => {
        console.log(`data : ${data}`)
        setData(data.message)}
        );
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          {!data ? "Loading..." : data}
        </p>
      </header>
    </div>
  );
}

export default App;

当我运行应用程序时(首先是

Node
,然后是
React
,我看不到
console.log('index page');
中的痕迹
controllers/index.js

我认为

react
消息尚未到达
node
。浏览器中的痕迹是:

App.js:12 got response [object Response]
App.js:16 data : undefined
App.js:17  Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'message')
    at App.js:17:1

进一步调试,我发现请求的响应是

304

请求是(url

/question

回答如下:

更多推荐

来自 React.js 应用程序的请求未命中 Node.js 后端端点

本文发布于:2024-05-31 06:27:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771368.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   后端   React   js   Node

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!