客户端有表单和按钮,我想将用户在表单中键入的数据发送到服务器,其中有请求处理程序将数据保存到数据库,从数据库发送到客户端.
我怎么能这样做我对逻辑很困惑,我认为有使用body解析器,还有什么是头文件的作用,在这种情况下请求选项,我发现解决方案但是我没有盲目实现,我只是我想在理解之后按照我的方式去做
在客户端:
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文件,如下所示:
所以首先你需要在index.html文件中添加http文件,如下所示:
<script src="node_modules/angular2/bundles/http.dev.js"></script>
并且您必须添加HTTP_PROVIDERS,无论是在引导程序的绑定还是在提供程序列表中.
所以现在来到RequestOptions,Headers等首先根据需要从这里导入这些……
import {Http,Response,RequestOptions,Headers,Request,RequestMethod} from 'angular2/http';
标题的作用:
基本上Header用于附加Content-Type或某种机密数据,如用户名,密码,我们要发送给服务器.
我们也有身体部分,也用于向服务器发送数据.例如:
this.headers = new Headers(); this.headers.append("Content-Type",'application/json'); this.headers.append("Authorization",'confidential data or something like that')
RequestOptions:
基本上RequestOptions是一些属性的集合,如方法(GET,POST,PUT ….),url或json文件的路径等,标题
身体部位等等.我们可以根据需要添加不同的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