Cant set Body of Post request using Angular HttpClient edit i am not able to make(put,delete,post any request...





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am new to Angular and Node I made Rest endpoint in NodeJS which looks like this
(update it works but only if i set the header of the request to application/x-www-form-urlencoded but then the requst body looks like {{"roleName":"new role"}: ""} this instaed of {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));
});
}


and I am making a post request from an angular application which looks like this



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


But the problem is I am unable to set the body of the request when using postman it works as it should but from angular, the body is always empty I even tried using fetch instead but the same issue is even tried setting the headers and methods in node app like this



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


but still, no success in making post request, however, get request works fine and I tries making a post request to this URL from json placeholder https://jsonplaceholder.typicode.com/posts it works fine I am unable to figure out what is the bug and I know the json link works cause it gives bakes the body of the request in the response and if i dont use JSON.Stringify i get corse error but as per the documentation is should work fine but it wont the get request looks like this



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


}



if i add {headers:httpHeader} with the requst i get cors error but if use it without it it works fine. cant make put delete or post request but they work in postman i even tried setting the content-type and Alloe-Acccess headers but nothing seems to be working



this is the angular service where i am making the request



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


this is the node code



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;


if i set header for get request even that brakes it










share|improve this question

























  • What does this line console.log(JSON.stringify(role)); in your addRole method log to the console?

    – SiddAjmera
    Jan 3 at 6:55











  • yes was using it to see that the data is getting there or not

    – Fahim Khan
    Jan 3 at 6:56











  • My question is, WHAT does it print on to the console? Can you please add the content that is logged to your question?

    – SiddAjmera
    Jan 3 at 6:57











  • the console.log in angular code prints "{"roleName":"newRole"}" (newRole is what i pass) and the console log in node part prints the request object with an empty body

    – Fahim Khan
    Jan 3 at 7:00











  • {"roleName":"d"} it logs this

    – Fahim Khan
    Jan 3 at 7:07


















0















I am new to Angular and Node I made Rest endpoint in NodeJS which looks like this
(update it works but only if i set the header of the request to application/x-www-form-urlencoded but then the requst body looks like {{"roleName":"new role"}: ""} this instaed of {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));
});
}


and I am making a post request from an angular application which looks like this



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


But the problem is I am unable to set the body of the request when using postman it works as it should but from angular, the body is always empty I even tried using fetch instead but the same issue is even tried setting the headers and methods in node app like this



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


but still, no success in making post request, however, get request works fine and I tries making a post request to this URL from json placeholder https://jsonplaceholder.typicode.com/posts it works fine I am unable to figure out what is the bug and I know the json link works cause it gives bakes the body of the request in the response and if i dont use JSON.Stringify i get corse error but as per the documentation is should work fine but it wont the get request looks like this



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


}



if i add {headers:httpHeader} with the requst i get cors error but if use it without it it works fine. cant make put delete or post request but they work in postman i even tried setting the content-type and Alloe-Acccess headers but nothing seems to be working



this is the angular service where i am making the request



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


this is the node code



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;


if i set header for get request even that brakes it










share|improve this question

























  • What does this line console.log(JSON.stringify(role)); in your addRole method log to the console?

    – SiddAjmera
    Jan 3 at 6:55











  • yes was using it to see that the data is getting there or not

    – Fahim Khan
    Jan 3 at 6:56











  • My question is, WHAT does it print on to the console? Can you please add the content that is logged to your question?

    – SiddAjmera
    Jan 3 at 6:57











  • the console.log in angular code prints "{"roleName":"newRole"}" (newRole is what i pass) and the console log in node part prints the request object with an empty body

    – Fahim Khan
    Jan 3 at 7:00











  • {"roleName":"d"} it logs this

    – Fahim Khan
    Jan 3 at 7:07














0












0








0








I am new to Angular and Node I made Rest endpoint in NodeJS which looks like this
(update it works but only if i set the header of the request to application/x-www-form-urlencoded but then the requst body looks like {{"roleName":"new role"}: ""} this instaed of {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));
});
}


and I am making a post request from an angular application which looks like this



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


But the problem is I am unable to set the body of the request when using postman it works as it should but from angular, the body is always empty I even tried using fetch instead but the same issue is even tried setting the headers and methods in node app like this



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


but still, no success in making post request, however, get request works fine and I tries making a post request to this URL from json placeholder https://jsonplaceholder.typicode.com/posts it works fine I am unable to figure out what is the bug and I know the json link works cause it gives bakes the body of the request in the response and if i dont use JSON.Stringify i get corse error but as per the documentation is should work fine but it wont the get request looks like this



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


}



if i add {headers:httpHeader} with the requst i get cors error but if use it without it it works fine. cant make put delete or post request but they work in postman i even tried setting the content-type and Alloe-Acccess headers but nothing seems to be working



this is the angular service where i am making the request



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


this is the node code



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;


if i set header for get request even that brakes it










share|improve this question
















I am new to Angular and Node I made Rest endpoint in NodeJS which looks like this
(update it works but only if i set the header of the request to application/x-www-form-urlencoded but then the requst body looks like {{"roleName":"new role"}: ""} this instaed of {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));
});
}


and I am making a post request from an angular application which looks like this



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


But the problem is I am unable to set the body of the request when using postman it works as it should but from angular, the body is always empty I even tried using fetch instead but the same issue is even tried setting the headers and methods in node app like this



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


but still, no success in making post request, however, get request works fine and I tries making a post request to this URL from json placeholder https://jsonplaceholder.typicode.com/posts it works fine I am unable to figure out what is the bug and I know the json link works cause it gives bakes the body of the request in the response and if i dont use JSON.Stringify i get corse error but as per the documentation is should work fine but it wont the get request looks like this



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


}



if i add {headers:httpHeader} with the requst i get cors error but if use it without it it works fine. cant make put delete or post request but they work in postman i even tried setting the content-type and Alloe-Acccess headers but nothing seems to be working



this is the angular service where i am making the request



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


this is the node code



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;


if i set header for get request even that brakes it







node.js angular express






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 11:35







Fahim Khan

















asked Jan 3 at 6:49









Fahim KhanFahim Khan

13




13













  • What does this line console.log(JSON.stringify(role)); in your addRole method log to the console?

    – SiddAjmera
    Jan 3 at 6:55











  • yes was using it to see that the data is getting there or not

    – Fahim Khan
    Jan 3 at 6:56











  • My question is, WHAT does it print on to the console? Can you please add the content that is logged to your question?

    – SiddAjmera
    Jan 3 at 6:57











  • the console.log in angular code prints "{"roleName":"newRole"}" (newRole is what i pass) and the console log in node part prints the request object with an empty body

    – Fahim Khan
    Jan 3 at 7:00











  • {"roleName":"d"} it logs this

    – Fahim Khan
    Jan 3 at 7:07



















  • What does this line console.log(JSON.stringify(role)); in your addRole method log to the console?

    – SiddAjmera
    Jan 3 at 6:55











  • yes was using it to see that the data is getting there or not

    – Fahim Khan
    Jan 3 at 6:56











  • My question is, WHAT does it print on to the console? Can you please add the content that is logged to your question?

    – SiddAjmera
    Jan 3 at 6:57











  • the console.log in angular code prints "{"roleName":"newRole"}" (newRole is what i pass) and the console log in node part prints the request object with an empty body

    – Fahim Khan
    Jan 3 at 7:00











  • {"roleName":"d"} it logs this

    – Fahim Khan
    Jan 3 at 7:07

















What does this line console.log(JSON.stringify(role)); in your addRole method log to the console?

– SiddAjmera
Jan 3 at 6:55





What does this line console.log(JSON.stringify(role)); in your addRole method log to the console?

– SiddAjmera
Jan 3 at 6:55













yes was using it to see that the data is getting there or not

– Fahim Khan
Jan 3 at 6:56





yes was using it to see that the data is getting there or not

– Fahim Khan
Jan 3 at 6:56













My question is, WHAT does it print on to the console? Can you please add the content that is logged to your question?

– SiddAjmera
Jan 3 at 6:57





My question is, WHAT does it print on to the console? Can you please add the content that is logged to your question?

– SiddAjmera
Jan 3 at 6:57













the console.log in angular code prints "{"roleName":"newRole"}" (newRole is what i pass) and the console log in node part prints the request object with an empty body

– Fahim Khan
Jan 3 at 7:00





the console.log in angular code prints "{"roleName":"newRole"}" (newRole is what i pass) and the console log in node part prints the request object with an empty body

– Fahim Khan
Jan 3 at 7:00













{"roleName":"d"} it logs this

– Fahim Khan
Jan 3 at 7:07





{"roleName":"d"} it logs this

– Fahim Khan
Jan 3 at 7:07












2 Answers
2






active

oldest

votes


















0














You don't need to stringify the body, you can pass the object itself. Just remove console.log(JSON.stringify(role)); and try.






share|improve this answer
























  • if i don't stringify then i get cors error

    – Fahim Khan
    Jan 3 at 7:41













  • Access to XMLHttpRequest at '127.0.0.1:3000/roles' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

    – Fahim Khan
    Jan 3 at 7:43











  • If the get request is working fine, can you please add the code to the question. You also need to fix whatever CORS error you are getting by adding proper headers to the request.

    – Sachin Gupta
    Jan 3 at 7:48











  • try setting in both angular and node

    – Sachin Gupta
    Jan 3 at 7:55











  • if i do it in angular even get request gives cors error

    – Fahim Khan
    Jan 3 at 7:56



















0














In your node js code try putting allow origin middle layer part before you are reading body of incoming request. That means you have to move body parser middle layer after allow origin part.For angular code in header just add content type. This is a guess, give this a try. Maybe this will help you.



---angular code---



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





share|improve this answer


























  • did that it works but only if set header to application/x-www-form-urlencoded but then the body looks like this {{"roleName":"new"}: ""} insted of {roleName: "new"}

    – Fahim Khan
    Jan 3 at 9:18











  • what is content type in your angular application?

    – R.Sarkar
    Jan 3 at 10:16











  • if set it aplication/json it gives cors error

    – Fahim Khan
    Jan 3 at 10:47











  • please show us the full angular code. including where you are setting the header.

    – R.Sarkar
    Jan 3 at 11:08











  • did se the qustion

    – Fahim Khan
    Jan 3 at 11:30












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54017543%2fcant-set-body-of-post-request-using-angular-httpclient-edit-i-am-not-able-to-mak%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You don't need to stringify the body, you can pass the object itself. Just remove console.log(JSON.stringify(role)); and try.






share|improve this answer
























  • if i don't stringify then i get cors error

    – Fahim Khan
    Jan 3 at 7:41













  • Access to XMLHttpRequest at '127.0.0.1:3000/roles' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

    – Fahim Khan
    Jan 3 at 7:43











  • If the get request is working fine, can you please add the code to the question. You also need to fix whatever CORS error you are getting by adding proper headers to the request.

    – Sachin Gupta
    Jan 3 at 7:48











  • try setting in both angular and node

    – Sachin Gupta
    Jan 3 at 7:55











  • if i do it in angular even get request gives cors error

    – Fahim Khan
    Jan 3 at 7:56
















0














You don't need to stringify the body, you can pass the object itself. Just remove console.log(JSON.stringify(role)); and try.






share|improve this answer
























  • if i don't stringify then i get cors error

    – Fahim Khan
    Jan 3 at 7:41













  • Access to XMLHttpRequest at '127.0.0.1:3000/roles' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

    – Fahim Khan
    Jan 3 at 7:43











  • If the get request is working fine, can you please add the code to the question. You also need to fix whatever CORS error you are getting by adding proper headers to the request.

    – Sachin Gupta
    Jan 3 at 7:48











  • try setting in both angular and node

    – Sachin Gupta
    Jan 3 at 7:55











  • if i do it in angular even get request gives cors error

    – Fahim Khan
    Jan 3 at 7:56














0












0








0







You don't need to stringify the body, you can pass the object itself. Just remove console.log(JSON.stringify(role)); and try.






share|improve this answer













You don't need to stringify the body, you can pass the object itself. Just remove console.log(JSON.stringify(role)); and try.







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 3 at 7:38









Sachin GuptaSachin Gupta

1,5531617




1,5531617













  • if i don't stringify then i get cors error

    – Fahim Khan
    Jan 3 at 7:41













  • Access to XMLHttpRequest at '127.0.0.1:3000/roles' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

    – Fahim Khan
    Jan 3 at 7:43











  • If the get request is working fine, can you please add the code to the question. You also need to fix whatever CORS error you are getting by adding proper headers to the request.

    – Sachin Gupta
    Jan 3 at 7:48











  • try setting in both angular and node

    – Sachin Gupta
    Jan 3 at 7:55











  • if i do it in angular even get request gives cors error

    – Fahim Khan
    Jan 3 at 7:56



















  • if i don't stringify then i get cors error

    – Fahim Khan
    Jan 3 at 7:41













  • Access to XMLHttpRequest at '127.0.0.1:3000/roles' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

    – Fahim Khan
    Jan 3 at 7:43











  • If the get request is working fine, can you please add the code to the question. You also need to fix whatever CORS error you are getting by adding proper headers to the request.

    – Sachin Gupta
    Jan 3 at 7:48











  • try setting in both angular and node

    – Sachin Gupta
    Jan 3 at 7:55











  • if i do it in angular even get request gives cors error

    – Fahim Khan
    Jan 3 at 7:56

















if i don't stringify then i get cors error

– Fahim Khan
Jan 3 at 7:41







if i don't stringify then i get cors error

– Fahim Khan
Jan 3 at 7:41















Access to XMLHttpRequest at '127.0.0.1:3000/roles' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

– Fahim Khan
Jan 3 at 7:43





Access to XMLHttpRequest at '127.0.0.1:3000/roles' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

– Fahim Khan
Jan 3 at 7:43













If the get request is working fine, can you please add the code to the question. You also need to fix whatever CORS error you are getting by adding proper headers to the request.

– Sachin Gupta
Jan 3 at 7:48





If the get request is working fine, can you please add the code to the question. You also need to fix whatever CORS error you are getting by adding proper headers to the request.

– Sachin Gupta
Jan 3 at 7:48













try setting in both angular and node

– Sachin Gupta
Jan 3 at 7:55





try setting in both angular and node

– Sachin Gupta
Jan 3 at 7:55













if i do it in angular even get request gives cors error

– Fahim Khan
Jan 3 at 7:56





if i do it in angular even get request gives cors error

– Fahim Khan
Jan 3 at 7:56













0














In your node js code try putting allow origin middle layer part before you are reading body of incoming request. That means you have to move body parser middle layer after allow origin part.For angular code in header just add content type. This is a guess, give this a try. Maybe this will help you.



---angular code---



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





share|improve this answer


























  • did that it works but only if set header to application/x-www-form-urlencoded but then the body looks like this {{"roleName":"new"}: ""} insted of {roleName: "new"}

    – Fahim Khan
    Jan 3 at 9:18











  • what is content type in your angular application?

    – R.Sarkar
    Jan 3 at 10:16











  • if set it aplication/json it gives cors error

    – Fahim Khan
    Jan 3 at 10:47











  • please show us the full angular code. including where you are setting the header.

    – R.Sarkar
    Jan 3 at 11:08











  • did se the qustion

    – Fahim Khan
    Jan 3 at 11:30
















0














In your node js code try putting allow origin middle layer part before you are reading body of incoming request. That means you have to move body parser middle layer after allow origin part.For angular code in header just add content type. This is a guess, give this a try. Maybe this will help you.



---angular code---



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





share|improve this answer


























  • did that it works but only if set header to application/x-www-form-urlencoded but then the body looks like this {{"roleName":"new"}: ""} insted of {roleName: "new"}

    – Fahim Khan
    Jan 3 at 9:18











  • what is content type in your angular application?

    – R.Sarkar
    Jan 3 at 10:16











  • if set it aplication/json it gives cors error

    – Fahim Khan
    Jan 3 at 10:47











  • please show us the full angular code. including where you are setting the header.

    – R.Sarkar
    Jan 3 at 11:08











  • did se the qustion

    – Fahim Khan
    Jan 3 at 11:30














0












0








0







In your node js code try putting allow origin middle layer part before you are reading body of incoming request. That means you have to move body parser middle layer after allow origin part.For angular code in header just add content type. This is a guess, give this a try. Maybe this will help you.



---angular code---



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





share|improve this answer















In your node js code try putting allow origin middle layer part before you are reading body of incoming request. That means you have to move body parser middle layer after allow origin part.For angular code in header just add content type. This is a guess, give this a try. Maybe this will help you.



---angular code---



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






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 3 at 17:55

























answered Jan 3 at 9:09









R.SarkarR.Sarkar

19616




19616













  • did that it works but only if set header to application/x-www-form-urlencoded but then the body looks like this {{"roleName":"new"}: ""} insted of {roleName: "new"}

    – Fahim Khan
    Jan 3 at 9:18











  • what is content type in your angular application?

    – R.Sarkar
    Jan 3 at 10:16











  • if set it aplication/json it gives cors error

    – Fahim Khan
    Jan 3 at 10:47











  • please show us the full angular code. including where you are setting the header.

    – R.Sarkar
    Jan 3 at 11:08











  • did se the qustion

    – Fahim Khan
    Jan 3 at 11:30



















  • did that it works but only if set header to application/x-www-form-urlencoded but then the body looks like this {{"roleName":"new"}: ""} insted of {roleName: "new"}

    – Fahim Khan
    Jan 3 at 9:18











  • what is content type in your angular application?

    – R.Sarkar
    Jan 3 at 10:16











  • if set it aplication/json it gives cors error

    – Fahim Khan
    Jan 3 at 10:47











  • please show us the full angular code. including where you are setting the header.

    – R.Sarkar
    Jan 3 at 11:08











  • did se the qustion

    – Fahim Khan
    Jan 3 at 11:30

















did that it works but only if set header to application/x-www-form-urlencoded but then the body looks like this {{"roleName":"new"}: ""} insted of {roleName: "new"}

– Fahim Khan
Jan 3 at 9:18





did that it works but only if set header to application/x-www-form-urlencoded but then the body looks like this {{"roleName":"new"}: ""} insted of {roleName: "new"}

– Fahim Khan
Jan 3 at 9:18













what is content type in your angular application?

– R.Sarkar
Jan 3 at 10:16





what is content type in your angular application?

– R.Sarkar
Jan 3 at 10:16













if set it aplication/json it gives cors error

– Fahim Khan
Jan 3 at 10:47





if set it aplication/json it gives cors error

– Fahim Khan
Jan 3 at 10:47













please show us the full angular code. including where you are setting the header.

– R.Sarkar
Jan 3 at 11:08





please show us the full angular code. including where you are setting the header.

– R.Sarkar
Jan 3 at 11:08













did se the qustion

– Fahim Khan
Jan 3 at 11:30





did se the qustion

– Fahim Khan
Jan 3 at 11:30


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54017543%2fcant-set-body-of-post-request-using-angular-httpclient-edit-i-am-not-able-to-mak%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

A Topological Invariant for $pi_3(U(n))$