[英]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.