我正在尝试做一个简单的待办事项列表应用程序来学习角度作为前端使用express作为后端,数据库使用sequelize进行管理。发布到节点后端以添加用户会生成此对象格式{ '{"first_name":"132","last_name":"132","email":"123"}': '' }
我找不到任何解析方法或更改数据发送方式。
以下是相关代码:
user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { throwError as observableThrowError, Observable } from
'rxjs';
import { Response } from '@angular/http';
import { User } from '../user';
import { catchError, shareReplay } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UserService {
url = "http://localhost:3000";
private headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
});
constructor(private http:HttpClient) {
}
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.url + '/users');
}
getUser(id: number): Observable<User[]> {
return this.http.get<User[]>(this.url + '/users/' + id);
}
addUser(user: User): Observable<User[]> {
const body = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email
}
return this.http.post<User[]>(this.url + '/adduser', body, { headers: this.headers, responseType: 'json'}).pipe(
catchError(response => { return observableThrowError(response); }));;
}
}
index.js(路线)
router.post('/adduser', /*cors(corsOptions),*/ function(req, res, next) {
console.log(req.body);
var firstName = req.body.first_name,
lastName = req.body.last_name,
email = req.body.email;
models.User.create({
first_name: firstName,
last_name: lastName,
email: email
}).then(function() {
res.send(200);
})
});
答案 0 :(得分:0)
使用HttpParams记录here
import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});
答案 1 :(得分:0)
user184994建议的工作代码
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { throwError as observableThrowError, Observable } from
'rxjs';
import { Response } from '@angular/http';
import { User } from '../user';
import { catchError, shareReplay } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UserService {
url = "http://localhost:3000";
constructor(private http:HttpClient) {
}
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.url + '/users');
}
getUser(id: number): Observable<User[]> {
return this.http.get<User[]>(this.url + '/users/' + id);
}
addUser(user: User): Observable<User[]> {
const body = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email
}
return this.http.post<User[]>(this.url + '/adduser', body).pipe(
catchError(response => { return observableThrowError(response); }));;
}
}