我最近開始學習MEAN堆棧,並遇到一個問題。我試圖從角度發送一個$ 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);
});
};
謝謝你的回答。我結束了使用req.query來訪問值,因爲params給我不確定。我會仔細閱讀一下,找出原因和是的,不用擔心,這是爲了學習的目的,我將來不會在URL中發送密碼。謝謝您的幫助! –
你說得對'關於req.query' - 抱歉。 'req.params'用於像'/ users /:userId'這樣的參數路由。 'req.params.userId'將包含用戶標識。我會解決我的答案。 –