簡體   English   中英

使用Express Js將Angular JS轉換為Node Js

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM