无法使用Angular HttpClient编辑设置Post请求的正文,我无法进行编辑(放置、删除、发布任何请求,只有g



我是Angular和Node的新手,我在NodeJS中创建了Rest端点,如下所示(更新它是有效的,但只有当我将请求的标题设置为application/x-www-form-urlencoded,但请求正文看起来像{{"roleName":"new role"}:"}这个{roleName:"newRole"}的实例)

public static routes(app: Application): void {
app
.route("/roles")
.get((req: Request, res: Response) => {
RoleC.allRoles().then(roles => res.status(200).send(roles));
})
.post((req: Request, res: Response) => {
console.log(req);
res.status(200).send(req.body);
// RoleC.addRole(req.body.roleName).then(r => res.status(200).send(r));
});
}

我正在从一个角度应用程序发出一个帖子请求,它看起来像这个

addRole(role: Role) {
console.log(JSON.stringify(role));
this.http
.post(this.baseURL, role)
.subscribe(e => console.log("r", e), err => console.log("er", err));
}

但问题是,当使用poster时,我无法设置请求的主体,它可以正常工作,但从角度来看,主体总是空的。我甚至尝试使用fetch,但同样的问题甚至尝试在像这样的节点应用程序中设置头和方法

this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({
extended: false
}));
this.app.all("*", (req: Request, res: Response, next: NextFunction) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With"
);
next();
});

但是,发出post请求仍然没有成功,然而,get请求运行良好,我尝试从json占位符向该URL发出post要求https://jsonplaceholder.typicode.com/posts它运行良好我无法弄清楚是什么错误,我知道json链接运行良好,因为它在响应中烘焙了请求的主体,如果我不使用json。Stringify我得到了corse错误,但根据文档,它应该运行良好,但它不会,得到的请求看起来像这个

Roles(): Observable<object> {
let httpHeaders = new HttpHeaders({
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
});
return this.http.get(this.baseURL);

}

如果我添加了带有requst的{headers:httpHeader},我会得到cors错误,但如果不使用它,它会正常工作。无法进行put-delete或post请求,但它们在poster中有效。我甚至尝试设置内容类型和Alloe-Access标头,但似乎什么都不起作用

这是我请求的角度服务

import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Role } from "./../models/role/role";
import { Injectable } from "@angular/core";
import { Subject, Observable } from "rxjs";
@Injectable({
providedIn: "root"
})
export class RoleService {
readonly baseURL = "http://127.0.0.1:3000/roles";
updateRole: Subject<Role[]> = new Subject<Role[]>();
private roles: Role[] = [];
constructor(private http: HttpClient) {}
get Roles(): Observable<object> {
let httpHeaders = new HttpHeaders({
"Content-Type": "application/json"
});
return this.http.get(this.baseURL);
}
getRole(id: number): Role {
return this.roles[id];
}
addRole(role: Role) {
let httpHeaders = new HttpHeaders({
"Access-Control-Allow-Headers":
"Content-Type, Authorization, Content-Length, X-Requested-With",
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
});
console.log(JSON.stringify(role));
this.http
.post(this.baseURL, role, { headers: httpHeaders })
.subscribe(e => console.log("r", e), err => console.log("er", err));
//this.updateRole.next(this.Roles);
}
}

这是节点代码

import * as express from "express";
import { Request, Response, NextFunction } from "express";
import * as bodyParser from "body-parser";
import IndexRoutes from "./routes/indexRoute";
import TestRoutes from "./routes/testRoute";
import UsersRoutes from "./routes/userRoute";
import RoleRoutes from "./routes/roleRoute";
import DepartmentRoutes from "./routes/department";
import RemunerationRoutes from "./routes/remunerationRouter";
import PayRoutes from "./routes/payRoute";
import FacultyRoutes from "./routes/FacultyRoute";
class App {
public app: express.Application;
constructor() {
this.app = express();
this.config();
IndexRoutes.routes(this.app);
TestRoutes.routes(this.app);
UsersRoutes.routes(this.app);
RoleRoutes.routes(this.app);
DepartmentRoutes.routes(this.app);
FacultyRoutes.routes(this.app);
RemunerationRoutes.routes(this.app);
PayRoutes.routes(this.app);
this.error();
}
private config(): void {
this.app.all("*", (req: Request, res: Response, next: NextFunction) => {
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With"
);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
next();
});
this.app.use(bodyParser.json());
}
private error(): void {
this.app.use((req: Request, res: Response) => {
res.status(404).send({
msg: <string>`404 ${req.path} not fount`
});
});
}
}
export default new App().app;

如果我为获取请求设置标题,即使这会使它停止

您不需要字符串化主体,您可以传递对象本身。只需移除console.log(JSON.stringify(role));并尝试。

在您的节点js代码中,在读取传入请求的主体之前,尝试放置allow-origin中间层部分。这意味着您必须将主体解析器的中间层移到allow-origin部分之后。对于标题中的角度代码,只需添加内容类型。这只是猜测,试试看。也许这会对你有所帮助。

---角度码

const httpOptions = {
headers: new HttpHeaders({
'Content-Type':  'application/json'
})
};
this.http
.post(this.baseURL, role,httpOptions )
.subscribe(e => console.log("r", e), err => console.log("er", err));
}

1)如果后端是nodejs,请确保安装"cors":

npm install --save cors 
npm install --save @types/cors 
import cors from 'cors';
app.use(cors());

2) 如果你能阅读你的身体,请确保你安装了"身体分析器":

npm install --save body-parser 
npm install --save @types/body-parser
import bodyParser , {urlencoded} from 'body-parser';
app.use(bodyParser.json());
app.use(urlencoded({ extended: true }));

如果问题仍然存在,请检查HttpInterceptor

最新更新