【问题标题】:Angular2: How to send data from client to server when making requestAngular2:发出请求时如何将数据从客户端发送到服务器
【发布时间】:2016-02-12 04:22:13
【问题描述】:

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

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

在客户端:

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

【问题讨论】:

    标签: angular angular2-http


    【解决方案1】:

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

    <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';
    

    页眉的作用:

    基本上 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 是一些属性的集合,例如method (GET,POST,PUT....)、url or path to json file etcHeaders 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

    【讨论】:

    • 我们还能用 GET 发送字符串吗?我尝试了 HTTT get(url, options),但我无法让 body 到达服务器,我错过了什么吗?
    • 不,我不认为通过 GET 请求可以发送正文部分。您可以使用 POST 请求和 PUT 请求发送正文部分。
    • 我想这是有道理的。但是我们来自 jQuery 背景,让我们在 GET 请求中传递一个数据 json 对象,它为我们将它们参数化。
    猜你喜欢
    • 2013-08-13
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多