无法使用nodeJs使app.post工作

时间:2017-04-22 21:22:36

标签: node.js angular

我正在尝试将Angular2连接到我的nodeJs服务器。我有一个验证表单,它发出了一个帖子请求。我想使用node来处理post请求。 但到目前为止,我无法使我的帖子请求正常工作。 console.log没有显示任何内容。 我缺少什么?

这是我的server.js,它指向我构建角度的文件夹dist

const express = require('express');
const path = require('path');
const http = require('http');

var walker = require('node-sync-walker');

const bodyParser = require('body-parser');


// Get our API routes
const api = require('./server/routes/api');

var app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

walker.routeWalker(__dirname + '/server/routes', app);

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

这是我的api.js

var users = [{username: "user", password: "password"}];

var router = require('express').Router();

module.exports = function(app) {
  router.post('/api/authenticate',
    function(req, res) {

      console.log("print something");

      let params = JSON.parse(req.body);

      // find if any user matches login credentials
      let filteredUsers = users.filter(user => {
          return user.username === params.username && user.password === params.password;
    });

      if (filteredUsers.length) {

        res.sendStatus(200);

      } else {
        console.log("print something else");

        return res.sendStatus(400)
      }

      //return;
    });
}

2 个答案:

答案 0 :(得分:0)

您将路线配置为'/ api / api / authenticate'

您应该从api.js

中的路线中删除'/ api'

答案 1 :(得分:0)

最后,它奏效了!我删除了api中的/api/authenticate @ catalacs建议。然后我改变了将模块路由器从api.js导入server.js的方式。

server.js

var users = [{username: "test", password: "test"}];

var router = require('express').Router();


  router.post('/authenticate',
    function(req, res) {

      console.log("print something");

      let params = JSON.parse(req.body);

      // find if any user matches login credentials
      let filteredUsers = users.filter(user => {
          return user.username === params.username && user.password === params.password;
    });

      if (filteredUsers.length) {

        res.sendStatus(200);

      } else {
        console.log("print something else");

        return res.sendStatus(400)
      }

      //return;
    });

module.exports = router;

在我的server.js中,我注释掉了这一行:

walker.routeWalker(__dirname + '/server/routes', router);