4

客户端有表单和一个按钮,我想将用户在表单中键入的数据发送到服务器,那里有将数据保存到数据库的请求处理程序,以及从数据库到客户端。

我该怎么做我对逻辑感到困惑,我认为使用了正文解析器,标题的作用是什么,在这种情况下请求选项,我找到了解决方案,但我没有盲目实施,我只是想明白后按我的方式做

在客户端:

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

1 回答 1

3

那么您的问题与HTTP即来自客户端和服务器端的数据交换有关。所以首先要做同样的事情,你必须需要在文件中添加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,例如我们要发送到服务器的。我们也有 body 部分,它也用于向服务器发送数据。例如:

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

请求选项:

基本上RequestOptions是一些属性的集合,例如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

于 2016-02-12T05:00:19.990 回答