[英]Why is my request body empty?
我最近开始学习MEAN堆栈,但遇到了问题。 我正在尝试从angular向我的本地服务器发送$ http.get请求,但是请求主体未定义。 奇怪的是我的帖子中并没有定义它。 我知道问题可能出在人体分析器上,我花了几个小时试图解决这个问题。 谢谢你的帮助!
这是我的快递代码:
var express = require('express');
var mongoose= require('mongoose');
var bodyParser=require('body-parser');
var http=require('http');
var db=mongoose.connect('mongodb://localhost:27017/checkIt');
var server = express();
var Schema= mongoose.Schema;
server.use(bodyParser.urlencoded({
extended: true
}));
server.use(bodyParser.json());
server.use(express.static(__dirname));
var UserSchema = new Schema({
username: String,
password: String
});
var User=mongoose.model('User',UserSchema);
server.post("/checkIt/users",function(req,res){
var newUser = new User({
username: req.body.username,
password: req.body.password
});
newUser.save(function(err,doc){
res.send("inserted");
});
});
server.get("/checkIt/users",function(req,res){
console.log(req.body);
var userToCheck= new User({
username:req.body.username,
password:req.body.password
});
User.findOne({username: userToCheck.username, password: userToCheck.password},function(err,obj){
res.send(obj);
});
});
server.listen(3000);
这是我的loginController,其中有我的get请求:
angular.module('app')
.controller('loginController',['$scope','$location', '$http',function($scope,$location,$http){
$scope.checkIfUser = function(){
var user={
username:$scope.username,
password:$scope.password
};
$http.get("http://localhost:3000/checkIt/users",user)
.success(function(response){
if(response===""){
console.log("User does not exist");
}
else goToHome();
});
};
var goToHome = function(){
$location.path('/Home')
}
}]);
最后,我不知道这是否有帮助,但这是我执行$ http.post请求的代码段
$scope.signup = function(){
createUser();
console.log(user);
$http.post("http://localhost:3000/checkIt/users",user)
.success(function(response){
console.log(response);
});
};
GET
不会有GET
! 生活就是这样。 没有消息体GET
。 现在解决问题。 您要在服务器端使用req.query
来访问值。
在Angular方面,您需要对代码进行一些更改(在url中发送密码是一件坏事):
$http.get('http://localhost:3000/checkIt/users', {
params: { username: $scope.username, password:$scope.password }
}).success(... same as before);
未定义请求主体是因为您无法通过GET
请求传递参数,您可能需要更改路由名称并改用POST
请求。
顺便说一句,将API请求移到UserService
并将其注入到控制器中可能会更干净一些,因为您最终将需要在其他地方重用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.