ReactJS/Express Axios POST 返回 404,来自 Postman

2024-01-03

我不知道我在这里做错了什么。 POST 方法适用于 Postman,但不适用于 React 前端。

users.js (/api/users/login)

// @route   POST api/users/login
// @desc    Login user / Returning JWT Token
// @access  Public
router.post('/login', (req, res, next) => {
  const { errors, isValid } = validateLoginInput(req.body);

  // Check validation
  if (!isValid) {
    return res.status(400).json(errors);
  }

  const email = req.body.email;
  const password = req.body.password;

  // Find user by email
  User.findOne({ email }) // matching email: email
    .then(user => {
      if (!user) {
        errors.email = 'User not found';
        return res.status(404).json(errors);
      }

    // Check Password
    bcrypt.compare(password, user.password)
      .then(isMatch => {
        if(isMatch) {

          // User matched. Create JWT payload
          const payload = {
            id: user.id
          } 

          // Sign Token
          jwt.sign(
            payload,
            keys.secretOrKey, 
            { expiresIn: 3600 }, 
            (err, token) => {
              res.json({
                success: true,
                token: 'Bearer ' + token
              });
          });
        } else {
          errors.password = 'Password incorrect'
          return res.status(400).json(errors);
        }
    });
  }); 
});

登录用户()函数:

export const loginUser = userData => dispatch => {
  axios
    .post("/api/users/login", userData)
    .then(res => {
      // Save to localStorage
      const { token } = res.data;
      // Set token to localStorage
      localStorage.setItem("jwtToken", token); // only stores strings
      // Set token to Auth header
      setAuthToken(token);
      // Decode token to get user data
      const decoded = jwt_decode(token);
      // Set current user
      dispatch(setCurrentUser(decoded));
    })
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

React 组件中的 onSubmit() 函数:

  onSubmit(e) {
    e.preventDefault();

    const userData = {
      email: this.state.email,
      password: this.state.password
    }

    this.props.loginUser(userData);
  }

Network:

Request URL: http://localhost:3000/api/users/login
Request Method: POST
Status Code: 404 Not Found
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Length: 155
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Mon, 16 Jul 2018 01:53:03 GMT
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 46
Content-Type: application/json;charset=UTF-8
Cookie: io=VtWk-hb742jVakwrAAAE; PHPSESSID=ige5g7257th8hiksjomg2khouu; i18next=en; connect.sid=s%3Aq6FkEveJbDYoKTy386QESFBxGaW8MjKd.qSBAkm2t23Ww4ZtHtcs7%2F1e5tDn528i0C6Hv7U3PwI0
Host: localhost:3000
Origin: http://localhost:3000
Referer: http://localhost:3000/login
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
{email: "[email protected] /cdn-cgi/l/email-protection", password: "admin"}
email
:
"[email protected] /cdn-cgi/l/email-protection"
password
:
"admin"

server.js 上的端口:

// Initializint the port
const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server running on port ${port}`));

我在这里检查了一些类似的问题,其中大部分与标题有关。就我而言,标头是 application/json,所以我认为问题不存在。通过 Postman 到达端点没有问题。


您的反应应用程序与后端应用程序运行在不同的端口上。create-react-app在端口 3000 上运行,正如您所说,您的后端在端口 5000 上运行。

当您的客户端应用程序向服务器发出请求时,它实际上向端口 3000 发出请求,如您在此处看到的。

请求网址:http://localhost:3000/api/users/login http://localhost:3000/api/users/login

这样做是因为您从未在请求​​中指定原始 url,如您在此处看到的post("/api/users/login", userData),在这种情况下,它默认为请求来自的同一端口,即端口 3000,而端口 3000 实际上没有您请求的 url。

您可以通过在请求中包含原始 url 或向 React 应用程序 package.json 添加代理来解决此问题,如下所示。

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development

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

ReactJS/Express Axios POST 返回 404,来自 Postman 的相关文章

随机推荐

  • Julia:为图书馆建立 OOP 模型的最佳方法是什么

    我正在尝试创建一个图书馆 假设我有一个模型 其中有一个输出 输入和描述函数的方程 输入为 x 1 2 3 4 5 6 y 5 2 4 8 9 2 我把它放入一个函数中 returns y values function fit x a b
  • flutter firebase 推送通知图标

    I made an app and I implemented push notifications and it works but I ve tried to change the default icon with a image p
  • 在 python 中使用 meshlab 函数

    我是 3D 新手 我有一个点云 我想使用 python 库形成一个网格 但我可以使用网格实验室函数 这些函数是 过滤器 gt 点集 gt 计算点集的法线 和 过滤器 gt 重新划分网格 简化和重建 gt 曲面重建 Poission 有没有什
  • 在 Azure VM 中使用 Booksleeve Redis 客户端时出现 Redis 连接错误

    我最近开始在新的 Azure VM 上托管我的一个业余项目 该应用程序使用 Redis 作为内存缓存 在我的本地环境中一切都工作正常 但现在我已将代码移至 Azure 我发现 Booksleeve 出现了一些奇怪的异常 当应用程序第一次启动
  • Powershell:引号解析不一致/奇怪的行为?

    全部 我正在尝试使用 PowerShell 编译程序 但该命令的解析方式很奇怪 此命令在 cmd exe 中正确执行 dmd od bin of bin convHull exe I src src concSort d src fileP
  • 如何左对齐 SWT ToolItem 中的文本?

    我正在升级 RCP 应用程序以使用 Eclipse 4 2 1 我遇到的问题之一是工具栏中文本的对齐方式发生了变化 我可以使用以下片段重现该问题 该片段改编自标准SWT 片段 http git eclipse org c platform
  • 如何在Python中重新分配列表中的项目?

    我想在 Python 中重新分配列表中的每个项目 In 20 l 1 2 3 4 5 In 21 for i in l i i 1 但名单根本没有改变 In 22 l Out 22 1 2 3 4 5 我想知道为什么会这样 任何人都可以详细
  • 网络浏览器是否需要在客户端计算机上安装 IE

    我只是想知道是否有任何版本的 I E 部署使用 webbrowser 控件的应用程序时必须安装在客户端计算机上 目标 net 2 平台 Thanks 当您使用 添加 删除 Windows 组件 小程序来 删除 Internet Explor
  • (VB6) 逐行读取文本文件查找特定单词

    下午好 StackOverflow 我刚刚在这里注册 我已经使用这个网站很多年了 它似乎总是提供答案的网站 所以我决定参与其中 废话不多说 这是我的问题 我正在为 LAN 各方编写一个 API 我和一个团队每月都会使用该 API 来帮助解决
  • 了解汇编级别 ++i 和 i++ 之间的区别

    我知道这个问题的变体已经在这里被问过多次 但我并不是在问两者之间有什么区别 只是想要一些帮助来理解这两种形式背后的组装 我认为我的问题与whys比到what的差异 我正在阅读Prata 的 C Primer Plus在处理增量运算符的部分
  • C++ select() 不等待超时时间

    我正在尝试使用 select 函数来接受输入 但如果用户没有输入任何内容 则每 2 秒执行一次其他操作 下面的代码在第一次到达 select 时等待两秒 但是一旦打印出第一个 超时 消息 它就会快速继续打印 超时 而不等待 2 秒 基本上进
  • Celery 任务在多个队列中注册

    我在 Django 1 9 中使用 celery 和 RabbitMQ 服务器 我有四个不同的队列 我正在这四个队列之一中注册一个任务 问题是我的所有任务都注册在所有四个队列中 就像我有一个名为add并有四个队列 A B C 和 D 理想情
  • 根据C++模板类型调用不同的C函数

    我的问题如下 我有一个 C 库 其中包含每个函数的多个版本 具体取决于它们所使用的数据类型 例如 void add double a double b double c and void sadd float a float b float
  • 如何设置 QComboBox 宽度以适合最大的项目?

    我有一个QComboBox我充满了QString using comboBox gt addItem someString 当我启动 GUI 应用程序时 QComboBox始终为 70 即使最小的项目要大得多 如何动态设置a的宽度QComb
  • 当我浏览 http://localhost:8004/elmah.axd 时,它会生成 404 错误

    当我浏览时http localhost 8004 elmah axd它显示应用程序中发生的错误 但也会生成 404 错误 我该如何停止这个 404 错误 404错误的详细信息是 System Web HttpException 0x8000
  • Visual Studio 2010 条件引用

    我们这里有多个产品共享一些公共库 这些库是单独解决方案的一部分 因此它们可以由TFS独立构建 但问题是在开发过程中 必须修改公共库 将其编译为二进制文件 将其复制到公共位置 编译产品解决方案 为了避免这种情况 我想知道是否可以有条件引用 因
  • 查看控制器 EXTJS 4 中的参考

    我无法在控制器中获取组合框值 组合框视图的getter方法返回 function i return this constructor apply this arguments null 而不是查看对象实例 如果我使用 var combo t
  • 未找到 QWebView 库

    当我尝试添加QWebFrame 库 我找不到它 并且答复是没有这样的文件或目录 所以知道为什么这个库不存在 我按如下方式添加库 include
  • 在 Curses 模式下,stdout 和 stderr 去哪里?

    当curses处于活动状态时 stdout和stderr去哪里 import curses sys def test streams print stdout print gt gt sys stderr stderr def curses
  • ReactJS/Express Axios POST 返回 404,来自 Postman

    我不知道我在这里做错了什么 POST 方法适用于 Postman 但不适用于 React 前端 users js api users login route POST api users login desc Login user Retu