[英]Angular JS to Node Js using Express Js
我一直在尝试通过expressJs在NodeJs服务器上运行angularJs前端。 该程序仅应采用用户输入并将其打印在服务器控制台上。 由于对JavaScript的了解有限,因此我编写了以下代码:
Client.js
angular.module("appModule",[]).
controller("appController", function($scope,$http){
$scope.action = function () {
console.log($scope.data);
var post = $http({
method: 'POST',
url: '/Data',
data: $scope.mod,
processData: false
})
post.success(function (response) {
console.log(response);
$scope.response.data = response;
});
}
});
Server.js
var express = require('express');
var fs = require("fs");
var url = require("url")
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/Data', function (req, res) {
console.log(req.body);
res.setHeader('Content-Type', 'application/json');
req.body.serverMessage = "NodeJS replying to angular"
res.end(JSON.stringify(req.body));
});
http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1),function (err,data){
if(err){
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(8081, function () {
console.log("Server running at http://127.0.0.1:8081/");
});
这似乎在终端上显示错误:
Server running at http://127.0.0.1:8081/
Request for /public/WebPageView.html received.
Request for /public/JavaScriptCode.js received.
Request for / received.
{ Error: ENOENT: no such file or directory, open ''
at Error (native) errno: -2, code: 'ENOENT', syscall: 'open', path: '' }
浏览器的场景如下浏览器屏幕
终端输出中的最后一个Request
显示它接收到/
请求。 您的代码提取/
在变量pathname
。 在fs.readFile
您提供第一个参数作为pathname.substr(1)
,因为路径名是/
here,所以可以归结为null
。 因此,您得到相应的错误。
@Ritik Saxena是正确的。 另外,由于您根本没有将Express连接到http服务器,因此实际上并没有让Express在上面的代码中完成它的工作。 您实际运行的唯一代码是http.createServer调用的回调。
您应该将快速应用传递给它,而不是自己的回调。 如果要运行现有的回调,则需要将其挂载为应用中间件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.