【问题标题】:Angular JS to Node Js using Express JsAngular JS 到 Node Js 使用 Express Js
【发布时间】:2017-01-15 13:25:24
【问题描述】:

我一直在尝试使用带有 expressJs 的 NodeJs 服务器运行 angularJs 前端。该程序仅应接受用户输入并将其打印在服务器控制台上。由于 JavaScript 知识有限,我编译了以下代码:

客户端.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;
            });
        }
});

服务器.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

【问题讨论】:

    标签: javascript angularjs node.js express


    【解决方案1】:

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

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

    【讨论】:

    • 你能告诉我该怎么做吗?
    【解决方案2】:

    终端输出中的最后一个Request 表明它收到了对/ 的请求。您的代码在变量pathname 中提取/。在fs.readFile 中,您将第一个参数提供为pathname.substr(1),归结为null,因为这里的路径名是/。因此,您会得到相应的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      相关资源
      最近更新 更多