Angular2: how to send data from client to server when executing a request

There is a form and a button on the client side, I want to send the data that the user entered in the form to a server where there is a request handler that saves data to the database and from the database to the client.

How can I do this, I got confused in the logic, I think that there is a use of the body parser, also what is the role of the headers, the query option in this case, I found this solution, but I do not perform the blind, I just want to do it my own way after understanding

On the client side:

let headers: Headers = new Headers();
headers.append('Content-Type', 'application/json');
let opts: RequestOptions = new RequestOptions();
opts.headers = headers;
this.http.post('http://localhost:
3000/addStudent',JSON.stringify(obj),opts).subscribe((res: Response) => {
             console.log(res.json())
             setTimeout(()=>{
            this.students = res.json();
        }, 3000)
         })   

On the server side:

app.post('/addStudent',function(req,res){
var newStudent = new StudentModel(req.body);
console.log(req.body);
newStudent.save();
StudentModel.find(function(err,data){
   if(err) res.send(err) 
   else{
       res.json(data)
   }
})
+4
source share
1 answer

, HTTP i.e . HTTP index.html :

<script src="node_modules/angular2/bundles/http.dev.js"></script>

HTTP_PROVIDERS .

RequestOptions, Headers etc. -, ...

import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';

:

Content-Type - , username,Password, . , . :

this.headers = new Headers();
    this.headers.append("Content-Type", 'application/json');
    this.headers.append("Authorization", 'confidential data or   
    something like that')

RequestOptions:

Bascially RequestOptions - , method (GET, POST, PUT....), url or path to json file etc, Headers body part . optipon . , RequestOptions.

this.requestoptions = new RequestOptions({
                method: RequestMethod.Post,
                url: "url path....",
                headers: this.headers,
                body: JSON.stringify(data)
            });

, . , .

@Pardeep.

http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

https://auth0.com/blog/2015/10/15/angular-2-series-part-3-using-http/

https://angular.io/docs/js/latest/api/http/Request-class.html

+3

Source: https://habr.com/ru/post/1628422/


All Articles