Angular POST请求不起作用

时间:2018-03-15 22:08:52

标签: angular http post request

我正在使用Express和Node来使API和Angular达到POST请求。 api工作正常,正如我在Postman中测试过的那样。问题出现在Angular代码中,当我使用此函数时它什么都不做。

这是authService:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators/map';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { of } from 'rxjs/observable/of';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const url = 'http://localhost:7171/login';

@Injectable()
export class AuthService {

  constructor(private http: HttpClient) { }
  login(username: string, password: string) {
    //do not need to stringify your body
    const body = {
        username, password
    }
    console.log(this.http.post(url));
    return this.http.get(url);
}

}

这是authComponent

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-loging',
  templateUrl: './loging.component.html',
  styleUrls: ['./loging.component.css']
})
export class LogingComponent implements OnInit {

  username: '';
  password: '';

  constructor(private router: Router, private auth: AuthService) { }

  login() {
    console.log(this.username, this.password);
    this.auth.login(this.username, this.password);
  }

  ngOnInit() {
  }
}

这是来自express的代码:

const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const async = require("async");


var connection = mysql.createConnection({
   [...]);


router.post('/login', function(req, res) {
    var inputName = req.body.user;
    var inputPass = req.body.password;
    console.log('Usuario: ' + inputName + '\nContraseña: '+inputPass);
    res.status(200).json({
        message: 'It Works',
        usuario: inputName,
        password: inputPass
    })
});

module.exports = router;

1 个答案:

答案 0 :(得分:2)

您已拨打this.auth.login(this.username, this.password),但您从未使用过该结果。 auth.login返回一个Observable,你需要订阅这样的结果:

this.auth.login(this.username, this.password)
         .subscribe(result => {
                       alert('OK');
                    }, 
                    error => {
                       alert('error occured');
                    });