尝试从客户端访问 Node/Express 端点时出现 404 Not Found

2024-02-07

我有一个 Node.js/Express REST API,可供前端 React 应用程序访问,用于库存管理系统,用于车库销售。当尝试添加新产品时,我尝试访问 POST 路由http://localhost:3001/api/new。然而,当我尝试访问它时,它会返回 404 Not Found 错误,尽管我确信我已经完成了让服务器可以看到路由所需的操作,以便客户端能够获取它。谁能告诉我我可能会缺少什么(如果有的话)?

从客户端访问端点:

const addNewItemHandler = async () => {
    setIsLoading(true);
        
    const REQUEST_BASE_URL = "http://localhost:3001";
    const REQUEST_ROUTE    = "/api/new";
    const REQUEST_URL      = `${REQUEST_BASE_URL}${REQUEST_ROUTE}`;

    const REQUEST_CONFIG = {
        method: "POST",
        body: JSON.stringify({
            "productID": productID,
            "name": productName,
            "quantity": quantity,
            "price": parseFloat(`${priceDollar}.${priceCents.split("")[0]}${priceCents.split("")[1]}`)
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    };

    try {
        await fetch(REQUEST_URL, REQUEST_CONFIG);
        setIsLoading(false);

        const currentItems = JSON.parse(localStorage.getItem('all-items'));
        const newItem = {
            id: productID,
            title: productName,
            quantity: quantity,
            price: parseFloat(`${priceDollar}.${priceCents.split("")[0]}${priceCents.split("")[1]}`)
        };

        localStorage.setItem('all-items', JSON.stringify([...currentItems, newItem]));

        history.push('/');
    } catch (err) {
        console.error(err);
        setIsLoading(false);
    }
};

服务器.js:

const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const sequelize = require('./db-config');
const apiRoutes = require('./routes/APIRoutes');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    );
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
  
    next();
});

app.use('/api', apiRoutes);

sequelize.sync().then(result => {
    app.listen(3001, console.log("Staring on port 3001"));
}).catch(error => {
    console.error(error);
});

APIRoutes.js

const express = require('express');
const router = express.Router();
const controller = require('../controller/Controller');

router.get('/all-items', controller.allitems);
router.get('/search/:term', controller.search);
router.get('/summary', controller.viewSummary);

router.post('/api/new', controller.createNewProduct);

router.patch('/sell-item', controller.sellProduct);

router.delete('/delete-all', controller.deleteAllProducts);
router.delete('/delete/:id', controller.deleteProduct);

module.exports = router;

控制器.js

const Sequelize = require('sequelize');
const Product = require('../models/Product');
const SoldProduct = require('../models/SoldProduct');
const Op = Sequelize.Op;

const allItems = (request, response) => {
    // ...
};

const search = (request, response) => {
    // ...
};

const viewSummary = (request, response) => {
    // ...
};

const createNewProduct = (request, response) => {
    const { productID, name, quantity, price } = request.body;

    Product.create({
        productID: productID,
        name: name,
        quantity: quantity,
        price: price
    }).then(() => {
        response.json({ message: "Successfully created a new product" });
    }).catch(error => {
        response.json({ message: "Something went wrong" });
    });
};

const sellProduct = (request, response) => {
    // ...
};

const deleteAllProducts = (request, response) => {
    // ...
};

const deleteProduct = (request, response) => {
    // ...
};

exports.allitems          = allItems;
exports.search            = search;
exports.viewSummary       = viewSummary;
exports.createNewProduct  = createNewProduct;
exports.sellProduct       = sellProduct;
exports.deleteAllProducts = deleteAllProducts;
exports.deleteProduct     = deleteProduct;

In server.js文件中,您将 APIRoutes.js 文件中的所有路由挂载到/api path:

app.use('/api', apiRoutes);

使用此配置时,URL 应为:http://localhost:3001/api/api/new.

您可以将您的路线安装到'/'路径,然后您就可以像以前一样访问您的路线。

app.use('/', apiRoutes);

或在APIRoute.js文件,你从/api/new只是/new

router.post('/new', controller.createNewProduct);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试从客户端访问 Node/Express 端点时出现 404 Not Found 的相关文章

随机推荐

  • 在同一服务器上加载同一项目的不同版本的配置文件的最佳方法是什么?

    我有一个大型 php 项目 依赖于两个级别的配置文件 在我的项目文件夹中 我有一个 default config ini 它被加载 然后与站点特定的配置文件合并 目前代码正在读取环境变量PROJECT CONFIG指向特定的配置文件 这对于
  • 我应该通过 SessionAware 还是 ActionContext 获取会话?

    在阅读了通过以下方式获取会话映射之间的差异之后ActionContext getContext getSession 并让它注入SessionAware我想知道哪种方法是首选方法 为什么 该API推荐使用SessionAware 我在网上读
  • 为什么 GetMessageW 会在我的 WPF 应用程序中占用大量 CPU 使用率?

    我在这里遇到了一个严重的难题 我正在调查应用程序中 WPF 组件的性能问题 我们的 net 应用程序非常大 并且几乎完全采用 Windows 窗体 作为新计划的一部分 我们使用丰富的 WPF 用户界面重写了我们的核心组件之一 有很多 Win
  • 为什么 git merge 有时会创建提交,有时不会?

    当我做git merge从另一个分支到当前工作区 git 有时会进行新的提交 Merge remote tracking branch xxx into xxx 有时 它不会 Fast forward src files 那么什么决定了是否
  • Mongoose findOne 在嵌套记录上无法按预期工作

    我在 MongoDB 中有一个集合 其简化版本如下所示 Dealers Id 123 Name Someone Email email protected cdn cgi l email protection Vehicles Id 123
  • 找不到 momd 文件:核心数据问题

    噢天啊 我搞砸了一些事情 我是一名 Core Data 菜鸟 正在开发我的第一个 iOS 应用程序 经过多次堆栈溢出后 我正在使用以下代码 NSString path NSBundle mainBundle pathForResource
  • Go 如何处理 Google App Engine 上的并发请求

    我对 Go 如何处理 Google App Engine 上的并发请求有点困惑 所以我希望有人能提供一些澄清 以下是我收集到的事实 Go 在 App Engine 上是单线程的 这是因为可以通过使用多个线程创建竞争条件来执行任意指针算术 h
  • 离子降低滚动速度

    我在尝试从此代码减慢滚动速度时遇到问题 ionicScrollDelegate getByHandle credit scrollBottom true 我怎样才能减慢滚动速度 因为现在它对我来说滚动得太快了 我需要放慢滚动速度 就像星球大
  • Python - 安装有扩展的远程 Webdriver

    我想使用以下命令在不同浏览器版本上测试一个扩展浏览器堆栈 http browserstack com 这是一个返回具有指定功能的驱动程序的函数 我有一个 crx file对于 Chrome 和 xpi file对于我本地计算机上的 Fire
  • 在屏幕上查找复合位置

    我正在 Java 中为 SWT 和 AWT 实现一个屏幕键盘 一件重要的事情是将键盘移动到可以显示所选文本字段的位置 并且不要位于屏幕键盘后面 对于 AWT 我可以检测当前选定组件的位置 Component owner KeyboardFo
  • 对有效的类型规则感到困惑

    我似乎再次错过了有关有效类型的一些难题 代码中的注释本质上是我的问题 但这是我能想到在适当的上下文中提出这个问题的唯一方法 include
  • 如何使用facet_grid或facet_wrap保持条的均匀厚度并切换条位置?

    我想用水平条形图显示数据并通过分组变量对其进行分面 因为我想要一个带有分面的水平图 所以我将使用geom barh来自ggstance包裹 我有一个数据集 其中我的观察结果被分为几种不同的类型和计数 像这样的事情 library tidyv
  • 导致Python的argparse执行默认操作

    我正在使用 argparse 的操作将各种数据添加到类中 如果命令行未提供该参数 我想对默认值使用该操作 这可能吗 谢谢 argparse不使用action当应用default 它只是使用setattr 它可能会使用type如果默认是字符串
  • 在PHP中按权重生成随机结果?

    我知道如何在 PHP 中生成随机数 但假设我想要一个 1 10 之间的随机数 但我想要更多的 3 4 5 然后是 8 9 10 这怎么可能 我会发布我尝试过的内容 但老实说 我什至不知道从哪里开始 基于 Allin 的answer http
  • 如何为子文档创建 mongoDb 模式

    我有如下文件 这里peoples包含指向用户集合的 ObjectId 数组 和contribution字段包含的子文档数量为peoples场地 长度是可变的 就像某个组有 2 个 ObjectId 一样people then contrib
  • 如何使 Plotly 图形动画工作

    你好 我正在尝试使用 Plotly v4 6 一切正常 我可以看到所有图表 除非我尝试从网站复制动画图表 import plotly express as px df px data gapminder px scatter df x gd
  • 如何将 wand.image.Image 转换为 PIL.Image?

    我花了一整天的时间来解决这个问题 但在堆栈溢出中没有看到答案 我尝试过这个但没有成功 gt gt pil image Image frombytes RGBA wand image size wand image make blob for
  • 无法解析:com.google.android:flexbox:1.1.0

    所以我正在尝试同步 android studio 项目 但 flexbox 始终无法解决 据我所知 所有相关的存储库都包含在内 我尝试了多个互联网连接 不涉及代理 但无济于事 我也尝试过不同版本的 Flexbox 这是我的应用程序 buil
  • 错误:PlatformNotSupportedException:不支持配置文件或 .NET Core 6 如何使用 SOAP .NET Framework wcf

    我有 Dot Net Framework 3 5 Web 服务 http www dneonline com calculator asmx http www dneonline com calculator asmx我想在 dot Net
  • 尝试从客户端访问 Node/Express 端点时出现 404 Not Found

    我有一个 Node js Express REST API 可供前端 React 应用程序访问 用于库存管理系统 用于车库销售 当尝试添加新产品时 我尝试访问 POST 路由http localhost 3001 api new 然而 当我