简体   繁体   English

NodeJS API 在浏览器上显示错误 404 但使用 Postman 运行

[英]NodeJS API display error 404 on browser but running using Postman

I am working with simple user signup and login with NodeJs and MongoDb.我正在使用 NodeJs 和 MongoDb 进行简单的用户注册和登录。 for GET and POST request, I am using Express Router as coded in user.js:对于 GET 和 POST 请求,我使用的是 user.js 中编码的 Express Router:

// Filename : user.js

const express = require("express");
const { check, validationResult} = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const router = express.Router();
const auth = require("../middleware/auth");
const User = require("../model/User");

/**
 * @method - POST
 * @param - /signup
 * @description - User SignUp
 */

router.post(`/signup`, //dipanggil untuk testing menggunakan cors pada single route
  [
    check("username", "Please Enter a Valid Username")
    .not()
    .isEmpty(),
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({min: 6})
  ],
    async (req, res) => {
      const errors = validationResult(req);
        if (!errors.isEmpty()) {
          return res.status(400).json({
            errors: errors.array()
          });
        }

      const {
        username,
        email,
        password
      } = req.body;
        try {
          let user = await User.findOne({ email });
          if (user) {
            return res.status(400).json({ msg: "User Already Exists" });
          }

          user = new User({
            username,
            email,
            password
          });

          const salt = await bcrypt.genSalt(10);
          user.password = await bcrypt.hash(password, salt);

          await user.save();
          const payload = {
            user: {
              id: user.id
            }
          };

          jwt.sign( payload, "randomString", { expiresIn: 10000 }, (err, token) => {
                  if (err) throw err;
                  res.status(200).json({token});
          });
          } catch (err) {
            console.log(err.message);
            res.status(500).send("Error in Saving");
          }
  }
);

/**
 * @method - POST
 * @description - User Login
 * @param - /user/login
 */

router.post("/login",
  [
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 6
    })
  ],
  async (req, res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const { email, password } = req.body;
    try {
      let user = await User.findOne({
        email
      });
      if (!user)
        return res.status(400).json({
          message: "User Not Exist"
        });

      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch)
        return res.status(400).json({
          message: "Incorrect Password !"
        });

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString",
        {
          expiresIn: 3600
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (e) {
      console.error(e);
      res.status(500).json({
        message: "Server Error"
      });
    }
  }
);

module.exports = router;

then I call user.js in index.js as coded:然后我在 index.js 中调用 user.js 作为编码:

const express = require("express");
const bodyParser = require("body-parser");
const InitiateMongoServer = require("./config/db");
const validationResult  = require("express-validator");
const user = require("./routes/user");

const PORT = process.env.PORT || 4000;
const app = express();

// Initiate Mongo Server
InitiateMongoServer();

//cors
const cors = require ('cors');
app.use(cors({ origin: true, credentials: true }));

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

/**
 * Router Middleware
 * Router - /user/*
 * Method - *
 */
app.use("/user", user);

app.get("/", (req, res) => {
  res.json({ message: "API Working" });
});


app.listen(PORT, (req, res) => {
  console.log(`Server Started at PORT ${PORT}`);
});

This result i got from postman:我从 postman 得到的这个结果:

在此处输入图像描述

and in the Browser, I got this:在浏览器中,我得到了这个:

在此处输入图像描述

As I mentioned, this code working when I tested on Postman, but keep display error when I tried to access the url in the browser.正如我所提到的,当我在 Postman 上测试时,这段代码可以工作,但是当我尝试在浏览器中访问 url 时仍然显示错误。 some recommendations I read that asked me to use CORS to solve the problem but after I tried, it's not working.我读到的一些建议要求我使用 CORS 来解决问题,但在我尝试之后,它不起作用。 I also add additional cors plugin in the browser (in this case, I tried using Mozilla and Chrome).我还在浏览器中添加了额外的 cors 插件(在这种情况下,我尝试使用 Mozilla 和 Chrome)。

I got stuck with this in two days.我在两天内就被困住了。 Hopefully, there is any kind of help for me希望对我有任何帮助

This is because when accessing a URL in a browser, it is using a GET request.这是因为在浏览器中访问 URL 时,它使用的是GET请求。 Since you haven't defined a GET endpoint in your API with that URL, it is returning a 404.由于您尚未使用 URL 在 API 中定义GET端点,因此它返回 404。

You can only access POST or other endpoints in browser using XHR or fetch requests.您只能使用 XHR 或获取请求访问POST或浏览器中的其他端点。

All the routes mentioned in your code are POST which cannot be triggered from a browser URL.您的代码中提到的所有路由都是 POST,不能从浏览器 URL 触发。 You can invoke a GET method using a browser and if you need to pass in arguments you can use querystring or params.您可以使用浏览器调用 GET 方法,如果需要传入 arguments,您可以使用查询字符串或参数。

you must add get method for default您必须为默认添加 get 方法

such这样的

 router.get('/',function (){})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未找到 Web API POST(在浏览器上抛出 404)但适用于 PostMan 和 Swagger - Web API POST not found (throws 404 on browser) but works on PostMan and Swagger 在使用 postman 测试基本 Nodejs CRUD API 时,出现错误“无法发布”。 如何解决这个问题? - While testing basic Nodejs CRUD API using postman, it gives error 'Cannot Post'. How to resolve this issue? API适用于Postman,但不适用于浏览器 - API works in Postman, but not on a browser 对运行SparkJava的localhost服务器的请求使用postman工作,但不能使用浏览器中的javascript - Requests to a localhost server running SparkJava work using postman, but not with javascript in a browser 使用nodejs并不断表达404错误 - Keep getting a 404 error using nodejs and express 在 Nginx 上运行的 NodeJS 应用程序中出现“net::ERR_ABORTED 404”错误 - "net::ERR_ABORTED 404" error in a NodeJS app running on Nginx POST 请求正在使用 POSTMAN,但是当我尝试使用 Axios 从浏览器(UI)调用相同的链接时,它显示 404 错误 | node.js - POST request is working using POSTMAN, but when I'm trying to call the same link using Axios from browser(UI) it's showing 404 error | node.js nodejs 和 twitter api 错误'错误:错误 Twitter 流式传输请求:404' - nodejs and twitter api error ' Error: Bad Twitter streaming request: 404 ' NodeJS 404错误 - NodeJS 404 Error NodeJS 错误:无法通过在 Web 浏览器上运行 url 获取/ - NodeJS Error: Cannot GET/ from running the url on the web browser
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM