In my angular app, I send a post
request to node API with JSON data object, but it doesn't work as intended. In the request payload, the JSON data object is not shown.
When i send a JSON string by using JSON.stringify(auth)
it's shown in the request payload but can't be parsed by the json body-parser
at the node backend. Requests body is empty. Give me a solution to this problem.
My code
import { Injectable } from "@angular/core";
import { AuthData } from "../modules/AuthData";
import {
HttpClient,
HttpParams,
HTTP_INTERCEPTORS,
HttpInterceptor,
HttpHeaders
} from "@angular/common/http";
@Injectable({
providedIn: "root"
})
export class AuthService {
private url = "http://localhost:3000";
private httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization: "my-auth-token",
"Request-Method": "post"
})
};
constructor(private http: HttpClient) {}
login(email: string, password: string) {
const authData = { email: email, password: password };
console.log(authData);
this.http
.post(this.url + "/api/user/login", authData)
.subscribe(response => {
console.log(response);
});
}
}
My backend code
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
const cors = require('cors');
const userRoute = require("./routes/user");
const app = express();
mongoose
.connect('mongodb://localhost:27017/tryondb', {
useNewUrlParser: true
})
.then(() => {
console.log("connected to the database");
})
.catch(() => {
console.log("connection failed");
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//var jsonParser = bodyParser.json();
//var urlencodedParser = bodyParser.urlencoded({ extended: false });
//app.use(cors);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Header",
"Origin, X-Requested-with, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS"
);
console.log("rrr");
next();
})
app.post("/api/user/login",(req,res,next)=>{
console.log(req);
});
app.use("/api/user", userRoute);
console.log("aaa");
module.exports = app;