node.js - Angular 服务快速 API 路由 + 发布数据

标签 node.js angularjs express

我正在将我的一个网站 ( http://maskedarmory.com ) 从 LAMP(使用 Laravel 4 MVC)转换为 MEAN 堆栈,到目前为止这是一个相当长的旅程。

我已成功启动并运行登陆页面,并将输入 POST 到我将其路由到的 Angular Controller 。

现在,我遇到的问题是让服务将 Angular 中的 POSTed 数据发送到 Express API。我一直在/api/character URL 路径上保留 404 Not Found 错误。

另外,如何访问工厂传递的 Angular 端的“characterData”变量?因为我正在尝试在服务器端的“characterData”变量上执行 console.log,并且我确信这超出了范围。

app/routes.js(快速路由)

// public/js/services/ArmoryService.js
angular.module('ArmoryService', []).
    factory('Armory', function($http) {

    return {
        // Get the specified character by its profile ID.
        get : function(id) {
            return $http.get('/api/character/' + id);
        },

        // call to POST and create a new character armory.
        create : function(characterData) {
            return $http.post('/api/character', characterData);
        }
    }
});

app/routes.js(快速路由)

module.exports = function(app) {

    app.post('/api/character', function(req, res) {
          console.log(characterData);
    });

    app.get('/', function(req, res) {
        res.sendfile('./public/index.html'); // load our public/index.html file
    });

};

如果我在 $http.post 到 API 之前执行 console.log,则“characterData”将拥有应有的所有信息。

我确信这是某种类型的路由问题,但如果我能弄清楚它,那我就该死了。

预先感谢您的帮助!

最佳答案

试试这个:

app.post('/api/character', function(req, res) {
  console.log(JSON.stringify(req.body));
  res.status(200).send('whatever you want to send back to angular side'); 
});

app.get('/api/character/:id', function(req, res) {
  console.log(req.params.id);
  res.status(200).send('whatever you want to send back to angular side''); 
});

关于node.js - Angular 服务快速 API 路由 + 发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25101735/

相关文章:

javascript - 使用 ADFS 和 nginx 实现 SSO

javascript - 如何使用selenium和同步JS进行截图

javascript - 使用angularJS在ng-bind中解析html

javascript - 使用 Express 的路由路径匹配 `/` 和 `/index`

javascript - 在 Node Express 应用程序中检测 TLS 版本?

node.js - 如何访问函数外部的变量

javascript - Mocha 测试 : 'TypeError: undefined not a function' at Test. serverAddress

javascript - AngularJS 将 {{post.title}} 更改为另一个 HTML 文件

javascript - Angular + Node(Express) + SSL 集成

node.js - Node.js 的 Swig 模板中使用括号错误