首页 > 解决方案 > 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>
  );
}

预先感谢您的支持。如果我不清楚,我会更好地向您解释这个问题。

标签: javascriptreactjsexpressfetch-api

解决方案


推荐阅读