gpt4 book ai didi

Angular POST 请求不起作用

转载 作者:可可西里 更新时间:2023-11-01 17:05:07 26 4
gpt4 key购买 nike

我使用 Express 和 Node 制作 API 和 Angular 来发送 POST 请求。正如我在 Postman 中测试的那样,api 工作正常。问题出在 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;

最佳答案

您调用了 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');
});

关于 Angular POST 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49310046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com