I'm currently working on a project where I need to send data from a reactive form to a REST API running on my local express.js server. The form consists of basic text input fields like name, surname, and email.
When the form data is submitted, it is sent to a service in the Form.Component.ts file as shown below:
onSubmit(formDirective)
{
this.personservice.senddata(this.personForm.value).subscribe(data=>{
console.log(data);
})
}
The service then handles posting the data to the REST API:
constructor(private http: HttpClient)
{
console.log('init PS')
}
getPeople(): Observable<People[]>
{
return this.http
.get<People[]>(this._peopleURL)
.map( (data: any) => data.people);
}
private _peopleURL = "http://localhost:8080/api/people";
senddata(data : any)
{
var body = JSON.stringify(data);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post(this._peopleURL, data);
}
Although the console log displays the correct data, I'm facing an issue where the data is not being posted to the REST API.
I have tried setting up my express.js server as outlined below:
const express = require('express');
const app = express();
const cors = require('cors')
var corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200
}
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use(cors(corsOptions))
app.listen(8080, () => {
console.log('Server gestartet');
});
app.route('/api/people').get((req, res) => {
res.send({
people: [
{ vorname: 'max', nachname: 'müller', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0b1a0c0b121e16133f18121e1613511c1012">[email protected]</a>', status: 'true', activity: 'Office' },
{ vorname: 'jeremy', nachname: 'püringer', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e9f3c3e4eee2eaefade0ecee">[email protected]</a>', status: 'true', activity: 'Office' },
{ vorname: 'peter', nachname: 'schmidt', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7d7e4d6f61787a6463236e65">[email protected]</a>', status: 'false', activity: 'service' }
]
});
});
app.route('/api/people/:vorname').get((req, res) => {
const requestedPersonSurname = req.params['vorname'];
res.send({ vorname: requestedPersonSurname });
});
app.route('/api/save').get()
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.route('/api/people').post((req, res) => {
res.send(201, req.body);
});