应用程序的请求未命中 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 后端端点
发布评论