Angular: data sending from form (with raw / json options)

angular 7 http post not working
httpoptions angular
angular httpclient headers
angular 2 http get example
angular 8 http get example
angular 6 post data to web api
save form data to json file in angular 6
angular http post not sending data

From my Angular 6 form I should send some data with the same configuration which I have in Postman (I send a screenshot with the complete configuration: as you can see, I chose the options but raw / Json).

I tried the following example but it doesn't work because I receive a "bad request 400" error message. This is my code which doesn't work:

public login() {

        let userPassword = this.registrationForm.get('password').value;
        let userLogin = this.registrationForm.get('email').value;
        let userLangKey = 'en';

        /*
        const transferObject = {

            password: userPassword,
            login: userLogin,
            langKey: userLangKey
        }

        JSON.stringify(transferObject);
        */

        const req = this.http.post('http://localhost:8080/api/register/', {
            password: userPassword,
            login: userLogin,
            langkey: userLangKey
        })
        .subscribe(
            res => {
            console.log(res);
        },
            err => {
            console.log("Error occured");
        }

      );
    }

I also tried to edit my code in this way but I receive the same error:

(...)

const httpOptions = {
            headers: new HttpHeaders({
              'Content-Type':  'application/json'
            })
        }; 

        const req = this.http.post('http://localhost:8080/api/register/', {
            password: userPassword,
            login: userLogin,
            langkey: userLangKey
            }, httpOptions)

        .subscribe(
            res => {
            console.log(res);
            },
            err => {
            console.log("Error occured");
            }

(...)

I'm not really sure how your form is built up so for this example I'm assuming you're using ngModel or you have already extracted the needed values from your form.

let l = 'test';
let p = 'pass';
let lk = 'en'

const transferObject = {
  login: l,
  password: p,
  langKey: lk
}

const object JSON.stringify(transferObject);

// requires injecting HttpClient in constructor
this.http.post<object>('http://myurl.com', string);

Then on the receiving end you can reverse this action to get your object back like so:

let string = // receive your string
const receivedObject = JSON.parse(string)

You can read more about the Javascript/Typescript JSON functions here: https://www.w3schools.com/js/js_json_stringify.asp

Angular: data sending from form (with raw / json options), from my Angular 6 form I should send some data with the same configuration which I have in Postman (I send a screenshot with the complete configuration: as​  Send Http Post with Angular 9/8 HttpClient by Example The HttpClient post() Method. You can send Http post requests using the HttpClient.post method.. According to the Angular docs.

Please use third parameter to set headers for this post request.

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};    
this.http.post<Hero>(this.heroesUrl, hero, httpOptions)

Communicating with backend services using HTTP, Applications often request JSON data from a server. These are the default values for those options, so the following examples do not pass the options object. Finally we use the post() method of HttpClient to send the form data to the server. For reference, FormData provides the following methods for working with form data: The FormData.append() appends a new value for an existing key, or adds the key if it does not exist. The FormData.delete() method deletes a key/value pair from a FormData object.

I tried myself and solved the problem; considering my last code version I posted here, all was correct and the once problem was simply activate. In the previous http row, I only define this.(blablabla); it was enough at the end of this row ".subscribe(blablabla)" to activate the function. Only this command; nothing else. Thank; I copy below my correct code. I hope, it can be useful for someone else.

public login() {

        let userPassword = this.registrationForm.get('password').value;
        let userLogin = this.registrationForm.get('email').value;
        let userLangKey = 'en';

        const transferObject = {

            password: userPassword,
            login: userLogin,
            langKey: userLangKey
        }

        let header:HttpHeaders = new HttpHeaders().set('Content-Type', 'application/json');

        const object = JSON.stringify(transferObject);
        const self = this;  

                //Here is the point!
        return self.httpClient.post(PathService.authPath()+'register', object, {headers: header}).subscribe((response: Response) => {

            this.helperService.snackBarWarning('all works correctly');
        });
    }

Angular 2: Using the HTTP Service to Write Data to an API, If successful, returns a 200 OK response, containing a JSON object JSON.​stringify(food); return this.http.post('/api/food/', body, options ) use API endpoints which return the saved object in JSON form. It seems that Angular 2 was not sending the Content-type: application/json headers with the requests. In this Angular FormData tutorial, we will understand how to use Angular 8/9/10 HttpClient API to Post FormData to a web server. Forms are an essential part of any web or mobile applications, and Forms allow us to gather data from the users and send that data to the webserver.

HttpClient.post body param is not sent correctly when using , Angular should send body object as an object, and not as the key of another object Because httpClient with header application/json works well. Should I need to create options route for each post request In the example he is using '​application/x-www-form-urlencoded' so we have to use form  NOTE: This does not use the "multipart/form-data" content type, which is primarily used for form posts that include binary file uploads. In general, I like posting data as JSON. But, it does require some preprocessing on the server. Sometimes, it's nice to just to deal with normal form data that the server can consume automatically.

Full Stack AngularJS for Java Developers: Build a Full-Featured , Build a Full-Featured Web Application from Scratch Using AngularJS with Clicking Body will bring up four options: form-data, x-www-form-urlencoded, raw, and binary. The drop-down menu has the following options: Text, Text (text/​plain), JSON (application/json), Use the blue Send button to send the HTTP request. Unlike simple requests (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send.

Ionic 5 HTTP POST with Angular by Example, In this example we'll be sending a simple JSON object. You can see how to post multipart form data in this tutorial. We also configured our Ionic 5/Angular application to use HttpClient and created (mocked) a REST server  To send data to the REST API is really simple with Angular HttpClient. Still, in the same API service file, add a function to POST data to the REST API. addSmartphone(smartphone: Smartphone): Observable<Smartphone> { return this.http.post<Smartphone>(localUrl, smartphone, httpOptions) .pipe( catchError(this.handleError('addSmartphone

Comments
  • You could read the form values and create an object yourself, then just call JSON.stringify on that object and send it as you send any other data.
  • Thank you very much for the absolutely quick response! Can you sent a little example, only i.e. whit one single data as an username? PS Make response as main question response and not here, so I can flag you as definitive solution!
  • Thank you! I have already retrieve my form data and convert with JSON.stringify; the problem is also not what happens after this operation because I should sent to a backend already developed and efficient. My only question is: how can I send this info to this backend? As you can see in attach "postman" configuration screenshot, all works correctly if in my "post" method to the link "localhost:8080/something..." I choose not "form" mode but "raw". Could you please sent me a row of example valid to send this info by post to this link but with "raw" option?
  • Thanks but it is referred to a database maybe, I don't see the way to insert my link and the JSON.stringify which you indicated me before... This is the only piece which is not yet present in my "mosaic"! Thank you very much.
  • I edited my main question with the application of your solution to my problem but I receive the same error; have I written something wrong? Thank you very much!
  • 'Content-Type', 'application/json' and JSON.stringify(dataToBeSent) is enough