reactjs - React fetch 到 Express API 不起作用,有什么提示吗?
问题描述
我正在尝试对我的 express api 进行简单的 fetch 调用,但我无法让它工作,响应为 200,但我得到的是 index.html 而不是我想要的 JSON。这是我的场景:
包.json
"version": "1.0.0",
"description": "Application to show FrontEnd knowledge",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --config webpack.config.js",
"build": "webpack --config webpack.config.js --mode production"
},
"proxy": "http://localhost:5000/",
反应组件代码
callBackendAPI = () => {
const body = fetch("/api/hello")
.then(res => res.text()) // convert to plain text
.then(text => console.log(text)) // then log it out
return body;re
};
表达 server.js 代码
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
})
// create a GET route
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
解决方案
从您的服务器代码看来,您正在发送回 JSON,但在您的前端代码中,您正在寻找文本。
callBackendAPI = () => {
const body = fetch("/api/hello")
.then(res => res.json())
.then(data => console.log(data.express))
};
推荐阅读
- docker - 如何设置与 docker 容器一起使用的 mysql 主机限制
- azure - 将在线 Azure 函数移动到本地 git 存储库的最佳方法是什么?
- node.js - 如何在有内容的节点 js 中创建全局搜索 api?
- javascript - 如何使用 rxjs 和 redux-observable 等待或监听 Url 的变化?
- python - 如何从文本文件创建字典并在 python 中添加值?
- java - Spring 创建两个 @Configuration bean 启动
- sql-server - (SQL) 服务器代理作业未停止
- python - Python:将库作为变量导入
- ffmpeg - 单个 FFMpeg 命令将 2 个音频与 1 个视频合并
- android - 用于长屏的 Android Layout 文件夹