javascript - React: fetch api 返回 index.html 页面
问题描述
今天我正在做一个个人项目,我遇到了 fetch api 的奇怪行为:每次我获取我的 API 内容(通过 fetch api,如果我手动编写“http://localhost:3001/api/images/some-id “在我的浏览器搜索栏中,它有效),系统返回主 index.html 页面。如果我尝试获取其他内容(即来自其他网站的一些占位符数据),一切正常。 我已经在我的客户端“package.json”中添加了“proxy”:“http://localhost:3001”,但这似乎根本不起作用。
这是我的 server.js 代码
'use strict';
const express = require('express');
const morgan = require('morgan');
const { param, validationResult } = require("express-validator");
const dao = require("./dao");
// init express
const app = express();
const port = 3001;
// global middleware
app.use(express.json())
app.use(morgan("dev"))
// get image by id
app.get("/api/images/:id",
[param("id").isInt({ min: 1, max: 100 })]
,(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ err: errors.array() });
}
dao.getImage(req.params.id)
.then((image) => {
if(image.error) res.status(404).json({"status":"failure", "message":image.error})
else res.status(200).json({"status":"success", message:image})
})
.catch((err) => {
res.status(500).json({
"message":`DataBase Error: ${err}`
})
})
})
// activate the server
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
只有一个可用的路由:“api/images/:id”返回一个对象,其中包含有关某个图像的所有信息,由 id 选择。现在,我的 API.js 代码:
const getImage = (id) => {
return fetch(`/api/images/${id}`)
.then(response => {
console.log(response) //here it prompts the html source code of index.html
if (!response.ok) {
throw Error(response.statusText);
}
return response
})
.then(response => response.text())
.catch(err => console.log(err));
}
const API = {
getImage
}
export default API
最后是我的 App.js 代码:
function App() {
useEffect(() => {
const foo = () =>{
API.getImage(1)
.then(data => console.log(data))
.catch(err => console.log(err))
}
foo()
}, [])
return (
<div className="App">
</div>
);
}
预先感谢您的支持。如果我不清楚,我会更好地向您解释这个问题。
解决方案
推荐阅读
- facebook - Facebook API:创建页面-“(#10)应用程序没有此操作的权限”
- python - plt.show 出现在终端而不是 Ipython 笔记本中
- python - python,Windows 7:ImportError:无法导入名称 X
- c# - ASPxComboBox 设置值
- javascript - 如何计算两次之间的剩余量以获得下一次削减的JavaScript?
- angularjs - 如何在angularjs中将文本框集中在表格ng-change中?
- sql - 死锁是否会导致任何活动连接超时/中断?
- unity3d - Unity - 一切都冻结在“ yield return new WaitForSeconds(); ”?
- laravel - Laravel 5.6 - 雄辩的创建不会接受数组
- c++ - C++ 模板 - 使用“std::is_same_v”而不是专门化并避免编译错误?