gpt4 book ai didi

node.js - Angular 6没有从expressjs Node 服务器获得响应

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:50 25 4
gpt4 key购买 nike

帮助菜鸟,我正在构建一个 MEAN 堆栈应用程序,我遇到了一个问题,我无法从 Express 服务器读取响应,但响应是在我使用 postman 时生成的,这是我的代码

auth.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { map } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class AuthService {

authToken: any;
user: any;
constructor(private http:Http) { }

registerUser(user){
let headers = new Headers();
headers.append('Content-Type','application/json');
return this.http.post('http://localhost:3000/users/register',user,
{headers: headers})
.pipe(map(res => res.json));
}

authenticateUser(user){
let headers = new Headers();
headers.append('Content-Type','application/json');
return this.http.post('http://localhost:3000/users/authenticate',user,
{headers: headers})
.pipe(map(res => res.json));
}
}

登录.组件.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';

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

username: String;
password: String;
constructor(private authService: AuthService,
private router: Router,
private flashMessage: FlashMessagesService
) { }

ngOnInit() {
}

onLoginSubmit(){
const user = {
username: this.username,
password: this.password
}
this.authService.authenticateUser(user).subscribe(data => {
console.log(data);
});
}
}

Chrome 控制台

ƒ () {                                         login.component.ts:29
if (typeof this._body === 'string') {
return JSON.parse(this._body);
}
if (this._body instanceof ArrayBuffer) {
return JSON.parse(this.text());

以下是 Postman 中的响应:

raw data...application/json login data and server response

最佳答案

错误出现在您的 pipe 函数中。

pipe(map( res => res.json ))

您需要在 map 内调用res.json()。将其转换为

pipe(map( res => res.json() ))

但是,Angular v5 不需要将响应转换为 JSON。

<小时/>

正确的代码如下:-

 authenticateUser(user){
let headers = new Headers();
headers.append('Content-Type','application/json');
return this.http.post('http://localhost:3000/users/authenticate',user,
{headers: headers})
.pipe(map(res => res.json()));
}

关于node.js - Angular 6没有从expressjs Node 服务器获得响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52002806/

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