0

I'm trying to post data (text input) from a reactive form to the REST API on my local express.js server. Name, surname, email... just basic text input fields.

here I send the value from Form to a service (Form.Component.ts)

  onSubmit(formDirective) 
 {
  this.personservice.senddata(this.personForm.value).subscribe(data=>{
  console.log(data);
  })
 }

And in the service I post 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);
  }

The console log displays the correct data but it doesn't post the data to the REST API. enter image description here

Which steps have I missed?

EDIT:

Here is the code for my express.js server

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: '[email protected]', status: 'true', activity: 'Office' }, 
      { vorname: 'jeremy', nachname: 'püringer', email: '[email protected]', status: 'true', activity: 'Office' },
      { vorname: 'peter', nachname: 'schmidt', email: '[email protected]', 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);
  });

1 Answer 1

1

Try this.

 senddata(data: any) {
    var body = JSON.stringify(data);
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');;
    return this.http.post(this._peopleURL, data);
  }

Notice that we are building the HTTPHeaders object by chaining successive set() methods. This is because HTTPHeaders is immutable, and its API methods do not cause object mutation. Instead, a call to set will return a new HTTPHeaders object containing the new value properties.

WORKING DEMO

Sign up to request clarification or add additional context in comments.

24 Comments

Thank you :) But it tells me that the type "void" can't be assigned to type "Headers" in this line: headers = headers.set('Content-Type', 'application/json; charset=utf-8');;
@JeremyPüringer: on which line?
headers = headers.set('Content-Type', 'application/json; charset=utf-8');;
make sure you are creating instance of HttpHeaders not Headers
Thanks :) Again, the values are being sent but not appearing in my REST api :/
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.