A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json
and includes the body
'{"text": "hello"}'
.
Below is the server code, which displays the request body and header:
import * as express from 'express';
import * as bodyParser from "body-parser";
const app = express();
const router = express.Router();
router.route("/home")
.all(bodyParser.json())
.all(function (req, res, next) {
console.log(req.body, req.headers['content-type']); // !!! print to console body and header
next();
})
.post( (req, res, next) => {
res.status(200).json({
message: req.body,
})
}
);
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, PATCH, PUT, POST, DELETE, OPTIONS");
next();
});
app.use('/api/v1', router);
app.listen(3000, function(){
console.log('listening on 3000');
});
The post request has been successfully tested using Postman and curl:
curl --location --request POST 'http://vm-gudiea.sio.lab.emc.com:3000/api/v1/home' --header 'Content-Type: application/json' --data-raw '{\"text\": \"hello\"}'
Both requests return the expected body and content-type
header.
{ text: 'hello' } 'application/json'
However, when attempting to send the same request from an Angular app, there seems to be an issue:
sendInitialRequest(): void {
const myHeaders = new HttpHeaders().set('Content-Type', 'application/json');
this.http.post(this.remoteUrl, JSON.stringify({text: 'hello'}), {headers: myHeaders})
.subscribe(data => console.log(data));
}
Calling this method results in the following output from the remote server:
{} undefined
It appears that the server did not receive the Content-Type
header and body for some reason. What could be causing this issue? How can I ensure successful transmission of post requests with both body and header from an Angular app?