无法使用Angular HttpClient设置发布请求主体,我无法创建(放置,删除,发布任何请求,只有get可以正常工作)

时间:2019-01-03 06:49:04

标签: node.js angular express

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

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

但仍然无法成功发出发布请求,但是,获取请求可以正常工作,我尝试通过json占位符https://jsonplaceholder.typicode.com/posts向该URL发出发布请求,它可以正常工作,但我无法确定是什么错误而且我知道json链接有效,因为它在响应中发出了请求的内容,如果我不使用JSON.Stringify,我会收到corse错误,但根据文档应该可以正常工作,但它不会像这样< / p>

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

}

如果我将{headers:httpHeader}添加到要求中,则会出现cors错误,但如果不使用它,它将正常工作。无法进行删除或发布请求,但它们在邮递员中工作,我什至尝试设置content-type和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;

如果我为获取请求设置了标头,即使它制止了它

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

在您的节点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));
 }

答案 2 :(得分:0)

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