使用Express Js将Angular JS转换为Node Js

时间:2017-01-15 13:25:24

标签: javascript angularjs node.js express

我一直在尝试使用带有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: '' }

浏览器的场景如下 Browser Screen

2 个答案:

答案 0 :(得分:1)

终端输出中的最后一个public MainPage() { this.InitializeComponent(); Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow); responseBlockTxt.Text = start(); } public string start() { var response = sendRequest(); System.Diagnostics.Debug.WriteLine(response); return ""; } public async Task<string> sendRequest() { using (var client = new HttpClient()) { var values = new Dictionary<string, string> { { "vote", "true" }, { "slug", "the-slug" } }; var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("URL/api.php", content); var responseString = await response.Content.ReadAsStringAsync(); return responseString; } } 显示它收到Request的请求。您的代码会在变量/中提取/。在pathname中,您提供的第一个参数为fs.readFile,归结为pathname.substr(1),因为此处的路径名为null。因此,您会收到相应的错误。

答案 1 :(得分:1)

@Ritik Saxena是对的。此外,您实际上并没有让Express在您上面的代码中执行此任务,因为您根本没有将其连接到http服务器。您实际运行的唯一代码是http.createServer调用的回调。

你应该将快递应用程序传递给它而不是你自己的回调。如果您希望现有的回调运行,则需要将其作为app中间件安装。