req.body在邮递员上运行时说未定义

时间:2018-07-30 09:30:05

标签: mysql node.js api express req

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

var con=mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"",
    database:"nodedb"
});

var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());


app.post('/reg', function (req, res) {     
    var name=req.body.user_name;
    console.log(name);

    con.query("SELECT * FROM users WHERE email = ?", [req.body.email],
    function(err,result){       
            if(result.length > 0){
            console.log('mail already exist');
            res.json('mail already exist');

            }
        else{
  con.query("INSERT INTO users (`name`,`email`,`contact`,`password`) VALUES (?,?,?,?) ",  [req.body.user_name,req.body.email,req.body.contact_no, req.body.user_password],
    function(err1,result1){
        if(err1){

        console.log('failed');  
        res.json(err1);
        }
        else{
            console.log('1 recoed inserted');   
            res.json(result1);

        }

 })
        }
})
}
  

req.body.user_name在控制台中未定义打印,在邮递员中为null。它   正在网页上但不在邮递员上。我现在应该怎么办。我浏览了许多网站,但没有得到答案。

3 个答案:

答案 0 :(得分:1)

您需要选择正确的标头内容类型:x-www-form-urlencoded

enter image description here

希望有帮助。

答案 1 :(得分:1)

在邮递员的正文中,确保您使用的是raw并将Application类型设置为Application / json,然后您可以提及

{
  "user_name": "Your_name"    
}

enter image description here

答案 2 :(得分:0)

您可能尚未初始化使用主体解析器的中间件。这是您的操作方法:

# save model and Preprocessor instance after partially training ktrain.get_predictor(model, preproc).save('/tmp/my_predictor') # reload Predictor and extract model model = ktrain.load_predictor('/tmp/my_predictor').model # re-instantiate Learner and continue training learner = ktrain.get_learner(model, train_data=trn, val_data=val) learner.fit_onecycle(2e-5, 1) 放入项目的入口点。