2017-04-22 58 views
0

我想連接我的Angular2到我的nodeJs服務器。我有一個身份驗證表單,它提出了一個請求。我想用node來處理post請求。 但到目前爲止,我無法讓我的發佈請求工作。 console.log不顯示任何內容。 我缺少什麼?無法使app.post工作使用nodeJs

這是我的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; 
    }); 
} 

回答

0

最後,它的工作!我刪除了 /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); 
0

要配置的路由作爲從API路線 '/ API/API /認證'

您應該刪除 '/ API'。 js

+0

我刪除了'api'如你所說。但是,當客戶端發出post請求api/authenticate時,節點控制檯中沒有任何內容。我期望在控制檯中「打印某些東西」。 – edkeveked