【问题标题】:Express router not working for post requests?快速路由器不适用于发布请求?
【发布时间】:2018-01-11 02:16:15
【问题描述】:

我正在使用带有以下 package.json 配置的 angular-cli 和 webpack:

"dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bcrypt-nodejs": "0.0.3",
    "body-parser": "^1.17.2",
    "core-js": "^2.4.1",
    "express": "^4.15.3",
    "express-session": "^1.15.4",
    "mongoose": "^4.11.3",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
} 

下面是我的根目录结构:

我正在使用 Angular2 学习 MEAN。我的 server.js 中有以下代码

const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
mongoose.connect("mongodb://localhost/demo");

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

const app = express();
app.use(session({
    secret: 'somesecrettokenhere',
    name: 'demo',
    resave: false,
    saveUninitialized: true
}));

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


app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../dist/index.html'));
});

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

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

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

/**
     * 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:

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

router.post('/login', (req, res) => {
  console.log('Run');
});

module.exports = router;

下面是我的 Angular2 service.ts:

import { Injectable } from '@angular/core';
import {Http, Response, Headers} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  constructor(private _http: Http) { }

      Login(email: string, password: string): Observable<Response> {
        let credentials = {
        _email: email,
        _password: password
      };
      return this._http.post('/api/login',{_uc:credentials}).map(
          (res: Response) => res.json()
      );
  }

}

问题:

当我点击我的表单提交按钮时,它会点击我的 service.ts 文件中的登录方法,但在服务器端控制台上没有显示任何错误或没有点击我的服务器 api.js 登录发布方法。我不知道为什么我的服务器端 api.js 登录发布方法没有命中并且在控制台窗口中没有显示任何错误。请告诉我我在代码中做错了什么。客户端代码是工作文件,我将控制台放在我的 service.ts 登录方法中,它向我显示输出,但 http 请求在服务器端不起作用。如果我的问题需要任何其他详细信息,请告诉我。

【问题讨论】:

    标签: node.js angular http express


    【解决方案1】:

    我认为这是您的错误,您在某些方面打错了

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

    试试改成

        app.use('/api', api);
    

    肯定会起作用,如果您要进行大型项目,理想的路线应该是不同的文件夹。

    只需要需要的文件在

    server.js

    如果您想修改路由命名约定,请查看express-namespace

    【讨论】:

    • mscdex 和 echonax 的答案解决了我的问题。感谢您的回答。
    【解决方案2】:

    您正在将 api.js 安装在“/routes”的基本 url (app.use('/routes', api);)。所以你可以通过 '/routes/login' 来访问它。

    如果这不是您想要的,则将其安装在“/api”,而不是像您的客户端代码所期望的那样。

    【讨论】:

      【解决方案3】:

      当我点击我的表单提交按钮时,它会点击我的 service.ts 上的登录方法

      您需要订阅 observable 才能“触发”它。

      示例:this.authService.Login(..).subscribe((res)=&gt; console.log(res));

      【讨论】:

      • 你说得对,我忘记订阅我的登录方法,所以我没有收到任何 404 错误。
      • @AhmerAliAhsan 和 mscdex 的回答,你的路径是错误的 :-) 但它没有引起我的注意 :-)
      • 你说得对,我的朋友。这是我的第一个基本错误:-)
      猜你喜欢
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      相关资源
      最近更新 更多