【问题标题】:Cant set Body of Post request using Angular HttpClient edit i am not able to make(put,delete,post any request only get is working)无法使用 Angular HttpClient 编辑设置 Post 请求正文我无法进行(放置、删除、发布任何请求,只有得到工作)
【发布时间】:2019-01-03 06:49:04
【问题描述】:

我是 Angular 和 Node 的新手,我在 NodeJS 中创建了 Rest 端点,看起来像这样 (更新它有效,但前提是我将请求的标头设置为 application/x-www-form-urlencoded 但请求主体看起来像 {{"roleName":"new role"}: ""} this instaed of {角色名称:“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));
    });
}

我正在从一个看起来像这样的 Angular 应用程序发出发布请求

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));
}

但问题是我无法在使用邮递员时设置请求的主体,但从角度来看,主体总是空的我什至尝试使用 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();
});

但是,发出发布请求仍然没有成功,但是,get 请求工作正常,我尝试从 json 占位符 https://jsonplaceholder.typicode.com/posts 向此 URL 发出发布请求它工作正常我无法弄清楚什么是错误,我知道 json 链接有效,因为它会在响应中烘烤请求的主体,如果我不使用 JSON.Stringify,我会收到严重错误,但根据文档应该可以正常工作,但它不会让 get 请求看起来像这样

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

}

如果我在请求中添加 {headers:httpHeader},我会收到 cors 错误,但如果在没有它的情况下使用它,它工作正常。无法发出删除或发布请求,但它们在邮递员中工作我什至尝试设置内容类型和 Alloe-Acccess 标头,但似乎没有任何工作

这是我提出请求的角度服务

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)); 在您的addRole 方法中记录到控制台的内容是什么?
  • yes 是用它来查看数据是否到达那里
  • 我的问题是,WHAT 它会打印到控制台上吗?您能否将记录的内容添加到您的问题中?
  • 角码中的console.log打印“{“roleName”:“newRole”}”(newRole是我通过的),并且控制台登录节点部分打印请求对象为空
  • {"roleName":"d"} 它记录了这个

标签: node.js angular express


【解决方案1】:

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

【讨论】:

  • 从源 'localhost:4200' 访问 XMLHttpRequest 在 '127.0.0.1:3000/roles' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态.
  • 如果获取请求工作正常,您能否将代码添加到问题中。您还需要通过向请求添加适当的标头来修复遇到的任何 CORS 错误。
  • 尝试在角度和节点中设置
  • 如果我用 Angular 进行操作,即使获取请求也会出现 cors 错误
  • 如果我在 Angular 中添加内容类型,即使我进行字符串化,也会出现 cors 错误
【解决方案2】:

在您的节点 js 代码中,尝试在您读取传入请求的正文之前放置允许来源中间层部分。这意味着您必须在允许来源部分之后移动正文解析器中间层。对于标题中的角度代码,只需添加内容类型。这是一个猜测,试试这个。也许这会对你有所帮助。

---角码---

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));
 }

【讨论】:

  • 它是否有效,但前提是将标头设置为 application/x-www-form-urlencoded 但主体看起来像这样 {{"roleName":"new"}: ""} insted {角色名称:“新”}
  • 您的 Angular 应用程序中的内容类型是什么?
  • 请给我们看完整的角码。包括您设置标题的位置。
  • 问题解决了
  • 如果我没有设置任何标题,我不会收到 cors 错误,但正文没有设置
【解决方案3】:

1) 如果您的后端是 nodejs,请确保您安装“cors”:

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

2) 如果您可以阅读您的正文,请确保安装“body-parser”:

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

【讨论】:

    猜你喜欢
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多