Angular2:如何在发出请求时将数据从客户端发送到服务器

Angular2: How to send data from client to server when making request

客户端有表单和按钮,我想将用户在表单中输入的数据发送到服务器,服务器有请求处理程序将数据保存到数据库,然后从数据库发送到客户端。

我怎么能这样做我对逻辑感到困惑,我认为有使用 body 解析器,还有 headers 的作用是什么,在那种情况下请求选项,我找到了解决方案,但我不是盲目实施,我只是想在理解后按照自己的方式去做

客户端:

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)
})   

在服务器端:

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)
})

您的问题与 HTTP 有关,即来自客户端和服务器端的数据交换。 所以首先做同样的事情,你必须需要在 index.html 文件中添加 http 文件,如下所示:

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

并且您必须添加 HTTP_PROVIDERS,无论是在 bootstrap 的连接处还是在供应商列表中。

所以现在来到 RequestOptions, Headers etc。首先根据需要从这里导入这些...

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

Header的角色:

基本上 Header 用于附加 Content-Type 或某种机密数据,如 username,Password ,我们要将其发送到服务器。 我们也有 body 部分,它也用于向服务器发送数据。例如:

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

请求选项:

基本上 RequestOptions 是某些属性的 collection,例如 method (GET,POST,PUT....), url or path to json file etc, Headers body part 等等。我们可以根据需要添加不同的选项。例如这里是使用 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