假设我有一个博客,允许用户提交帖子 新帖子页面链接是 /new 下面是帖子路由逻辑
//NEW POST LOGIC
router.post("/", function(req, res) {
var data = {title : req.body.title, image: req.body.image, content: req.body.content};
Blog.create(data, function(err, blogPost) {
if(err){
res.send("error");
} else {
res.redirect("/");
}
});
});
Run Code Online (Sandbox Code Playgroud)
这次我可以为用户登录创建另一个帖子路由吗登录页面是 /login 来自操作是相同的 -
router.post("/", function(req, res) {
Run Code Online (Sandbox Code Playgroud)
................ });
像这样的东西会起作用吗?如果不行的话会导致什么问题?
在 Express 中创建路线时,您有 2 个选择
1 - 为同一路由创建不同的 HTTP 方法
例子:
app.GET('/login',(req,res)=>{ res.send("Get the login page"); });
app.POST('/login',(req,res)=>{ res.send("POST the login page data"); });
Run Code Online (Sandbox Code Playgroud)
2 - 为不同的路由创建不同的 HTTP 方法
例子:
app.GET('/profile',(req,res)=>{ res.send("Get the profile page"); });
app.GET('/home',(req,res)=>{ res.send("GET the home page"); });
app.POST('/contact-Form',(req,res)=>{ res.send("POSTthe contact form page"); });
app.POST('/register',(req,res)=>{ res.send("POST the register page data"); });
Run Code Online (Sandbox Code Playgroud)
您不能对同一路由使用相同的 HTTP 方法。
例子
app.GET('/login',(req,res)=>{ res.send("FIRST GET METHOD"); });
app.GET('/login',(req,res)=>{ res.send("SECOND GET METHOD"); });
Run Code Online (Sandbox Code Playgroud)
或者
app.POST('/login',(req,res)=>{ res.send("FIRST POST METHOD"); });
app.POST('/login',(req,res)=>{ res.send("SECOND POST METHOD"); });
Run Code Online (Sandbox Code Playgroud)
希望这有帮助:)
| 归档时间: |
|
| 查看次数: |
3567 次 |
| 最近记录: |