客户端上有一个表单和一个按钮,我想将用户在表单中键入的数据发送到服务器,服务器上有将数据保存到数据库以及从数据库保存到客户端的请求处理程序。
我该怎么做,我对逻辑感到困惑,我认为这里使用主体解析器,在这种情况下,标题,请求选项的作用是什么,我找到了解决方案,但我不是盲目实现,我只是想在理解后以自己的方式做
在客户端:
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
客户端和服务器端的数据交换有关。所以首先要做同样的事情,您需要像这样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';
基本上,Header用于附加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')
BasciallyRequestOptions
是像一些properts的集合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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句