TransWikia.com

Как правильно использовать express.bodyParser()?

Stack Overflow на русском Asked by MarEeee on December 14, 2020

Подскажите пожалуйста, почему мне не удается подключить и использовать express.bodyParser? Как я могу это сделать?

app.use(express.static(__dirname + '/dist'));

app.use(todoRoutes);



function start (){
    try {
        app.listen(PORT, () =>{
            console.log("Server has been statred...")
        });
    }
    catch(e){
        console.log(e);
    }
}

start();
const {Router} = require('express');
const router = Router();
var foo = require("../script.js");

router.configure(function(){
    router.use(express.bodyParser());
  });
  

const path = require('path');
var myModule = require('../index.js');

router.get('/', (req, res)=> {
    res.sendFile(path.resolve('./dist/index.html'));
});

router.post('/1',(req, res) =>{  // отправка первого экрана
    console.log("POST");
    res.sendFile(path.resolve('./data/firstScreen.json'));
})

router.post('/2',(req, res) =>{  // отправка второго экрана
    console.log("POST");
    res.sendFile(path.resolve('./data/secondScreen.json'));
})

router.post('/currentDir1', (req, res) =>{  
        console.log("POST");
        
        let body = "";   
        let pathToFile = "";
        console.log(req.body);        
        
        req.on("data", function (data) {
            body += data;
        });
        
        req.on("end", function(currentData) {
            console.log(JSON.parse(body));
            currentData = JSON.parse(body);
            
    
            if(currentData.sizeOrType === "<папка>"){
                let dir = currentData.dir + currentData.fileName;
                // dir = "C:\totalcmd";
                console.log(dir);                
                if(currentData.whichScreen){
                    console.log(currentData.whichScreen);
                    console.log("ggg");
                    foo(dir, './data/firstScreen.json');
                    pathToFile = './data/firstScreen.json';
                    res.sendFile(path.resolve('./data/firstScreen.json'));
                }else{
                    console.log('aaaa');
                    foo(dir, './data/secondScreen.json');
                    pathToFile = './data/firstScreen.json';
                    res.sendFile(path.resolve('./data/secondScreen.json'));
                    
                }        
            }
        
            // // res.json({ message: 'goodbye'})   
            res.sendFile(path.resolve('./data/firstScreen.json'));     
        });
           
        // res.sendFile(path.resolve(pathToFile));
    })


module.exports = router;

One Answer

Если посмотреть документацию

то есть несколько примеров использования

пример с Express/Connect top-level generic

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:n')
  res.end(JSON.stringify(req.body, null, 2))
})

Express route-specific

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  res.send('welcome, ' + req.body.username)
})

// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  // create user in req.body
})

у Вас думаю начало будет примерно так

const {Router} = require('express'); 
const router = Router();
var foo = require("../script.js");

var bodyParser = require('body-parser')

//router.configure(function(){
//   router.use(express.bodyParser());
//});

// parse application/json
router.use(bodyParser.json())
...  

Answered by Aziz Umarov on December 14, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP