[英]Cannot post data from Angular.js to Node.js
I am creating a MEAN stack application using AngularJS and Node.js. 我正在使用AngularJS和Node.js创建MEAN堆栈应用程序。
Here is my AngularJS code: 这是我的AngularJS代码:
app.js: app.js:
var app = angular.module('crudApp', ['ngRoute']);
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider){
$routeProvider
.when('/employees/create', {
templateUrl : 'create.html',
controller : 'EmployeeController'
}).when('/nothing', {
templateUrl : 'main.html',
controller : 'mainController'
});
$locationProvider.html5Mode(true);
}]);
app.controller('EmployeeController',function($scope,$http) {
$scope.save = function(data) {
$scope.data = JSON.stringify(data);
console.log(data);
$http.post("http://localhost:8080/employees/create-employee",$scope.data).then(function(response) {
console.log("posted successfully");
});
};
});
Here is my Node.js code: 这是我的Node.js代码:
server.js: server.js:
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(express.static(__dirname + '/angularjs/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('*',function(req, res) {
res.sendFile(__dirname + '/angularjs/public/index.html');
});
require('./node/routes')(app);
app.listen(8080);
routes.js: routes.js:
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.body);
});
Angular part is working fine, displays data in console, posting the data and getting "posted successfully" message. Angular部分工作正常,在控制台中显示数据,发布数据并获得“成功发布”消息。
But in node, I am unable to get the posted data in req.body. 但是在节点中,我无法在req.body中获取发布的数据。
I am getting the "create.html" content when I checked in browser "network". 当我在浏览器“网络”中签入时,我正在获取“ create.html”内容。
Need someone's help. 需要别人的帮助。
Use this 用这个
module.exports = function(app) {
app.post('/employees/create-employee',function(req,res) {
console.log(req.body);
});
And for get you should use req.params 为了得到你应该使用req.params
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.params);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.