简体   繁体   English

node js express app.get 和 app.post 不起作用

[英]node js express app.get and app.post does not work

i wrote a code sample for express js and it is working but when I use app.post or app.get instead of app.use the code does not work and the ide (webstorm) does not recognize the app.post or app.get too我为 express js 编写了一个代码示例,它正在运行,但是当我使用 app.post 或 app.get 而不是 app.use 时,代码不起作用并且 ide(webstorm)无法识别 app.post 或 app.get也

is it replaced with something in the newer versions of express or something?它是否被较新版本的 express 或其他东西所取代? here is my code:这是我的代码:

const express = require('express');
let app = express();
app.use('/addp',(req,res,next)=>{
    res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({extended:true}));
     //next line does not work 
    //if I use app.use it will work fine
app.get("/product",(req,res)=>{
    console.log(req.body);
    res.redirect('/');
})
app.use('/',(req,res)=>{
    res.send("<h1>done</h1>")
})
app.listen(3000);

Your code is working fine.您的代码运行良好。 For the print body, you should have to use bodyParser in express js.对于打印正文,您应该必须在 express js 中使用bodyParser

   const express = require('express');
let app = express();
var bodyParser = require('body-parser')

app.use('/addp', (req, res, next) => {
  res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})

app.use(express.urlencoded({ extended: true }));
app.use(
  bodyParser.json({
    limit: "250mb"
  })
);
app.use(
  bodyParser.urlencoded({
    limit: "250mb",
    extended: true,
    parameterLimit: 250000
  })
);

app.get("/product", (req, res) => {
  res.send("Get Request")
})

app.post("/product", (req, res) => {
  console.log("-------------")
  console.log(req.body);
  console.log("-------------")
  res.send("Post Request")
})

app.use('/', (req, res) => {
  res.send("<h1>done</h1>")
})

app.listen(3000);

It is this:就是这个:

app.route('/product/').get(function (req, res) {

If u want to add multiple routes let's say api, u will do this: In some module api.js:如果你想添加多个路由,比如说 api,你会这样做:在某些模块 api.js 中:

const apiRoutes = express.Router();
apiRoutes.get('/some', () => {});
apiRoutes.post('/some', () => {});

Then let's say your server:然后让我们说你的服务器:

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM