客户端有表单和一个按钮,我想将用户在表单中键入的数据发送到服务器,那里有将数据保存到数据库的请求处理程序,以及从数据库到客户端。
我该怎么做我对逻辑感到困惑,我认为使用了正文解析器,标题的作用是什么,在这种情况下请求选项,我找到了解决方案,但我没有盲目实施,我只是想明白后按我的方式做
在客户端:
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)
})