从客户端的javascript我发送每个ajax帖子3个变量,并在服务器上我尝试查看客户端的json内容,它显示我未定义,我不知道问题出在哪里,我附上代码(重构):
文件:./路由/索引.js
'use strict'
const express = require('express')
const user_controller = require('../controller/user')
const api = express.Router()
// pagina de Inicio
api.get('/index',function(req,res){
res.render('index')
})
// Gestion de usuarios
api.get('/usuarios',user_controller.getAllUsers)
api.post('/usuarios',user_controller.newUser)
api.get('/usuario',user_controller.getUser)
api.post('/logear',user_controller.logear)
api.post('/registrar',user_controller.registrar)
module.exports = api
文件:./ controller / user.js
function registrar(req,res){
var bcrypt = require('bcrypt');
var BCRYPT_SALT_ROUNDS = 12;
var user = req.body.user;
var email = req.body.email;
var pass = req.body.pass;
console.log('info: ' + user + ' ' + email + ' ' +pass);
//console.log('perro: ' + req.body);
// encriptamos la contraseña
bcrypt.genSalt(10, function(err, salt) {
if(error) throw error;
else{
bcrypt.hash(pass, BCRYPT_SALT_ROUNDS, function(err, hash) {
pass = hash;
});
}
});
//bcrypt.hash(pass, BCRYPT_SALT_ROUNDS).then(function(hashedPassword) {pass = hashedPassword});
conexion_db.query({ ... etc
file:./ app.js
'use strict'
//configuracion del servidor
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.set('view engine','jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
const api = require('./routes');
app.use('/api',api);
module.exports = app
file:client.js
$.ajax({
url: 'http://localhost:3000/api/registrar',
data: JSON.stringify({'user': $('#nick').val(),'email': $('#email').val(),'pass': $('#pass').val()}),
type: "POST",
dataType: 'json',
success: function(json) {
console.log("json: " + json.estado);
console.log("json: " + json.user);
console.log("json: " + json.pass);
我上了cmd服务器,这个:info:undefined undefined undefined
答案 0 :(得分:0)
bodyParser中间件无法处理json数据,因为您尚未设置ContentType.jQuery ajax内容类型参数的默认值为" application / x-www-form-urlencoded; charset = UTF-8"。但是你要以json类型发送数据。你需要将ContentType设置为 application / json。
您也可以将PlainObject提供给数据参数。