将数据传递给服务器的更好方法?

时间:2017-07-27 16:56:40

标签: javascript http

所以我使用查询字符串将数据从表单传递到我的服务器。查询字符串如下所示:

this.$http.post('http://localhost:3000/operation?Stime='+this.Stime+'&Etime='+this.Etime+'&eAMPM='+this.eAMPM+'&sAMPM='+this.sAMPM+'&id='+this.id+'&activity='+this.activity+'&auto_insert='+this.auto_insert+'&yearmonthday='+this.yearmonthday+'&color1='+this.c)

并且在我的服务器中,我有所有这些变量来存储查询的变量:

var color = req.query.color1; 
var Stime = req.query.Stime; 
var Etime = req.query.Etime;
var sAMPM = req.query.sAMPM;
var eAMPM = req.query.eAMPM;
var id = req.query.id;
var activity = req.query.activity;
var requestAccepted = req.query.requestAccepted;
var yearmonthday = req.query.yearmonthday;
var auto_insert = req.query.auto_insert;

将变量发布到服务器似乎有很多代码(它工作得很好)但我想知道是否有一些方法可以重构它/使其更清洁

1 个答案:

答案 0 :(得分:0)

当然有!

考虑对HTTP消息体进行一些研究:

  

消息体是从服务器(包括文件,图像等)携带实际HTTP请求数据(包括表单数据和上传等)和HTTP响应数据的消息体。

在您的情况下,您可以将Angular $ http POST请求更改为 -

var data = { 
  Stime: '+this.Stime+',
  Etime: '+this.Etime+',
  eAMPM: '+this.eAMPM+',
  sAMPM: '+this.sAMPM+',
  id: '+this.id+',
  activity: '+this.activity+',
  auto_insert: '+this.auto_insert+',
  yearmonthday: '+this.yearmonthday+', 
  color1: '+this.c+'
}

$http({
  method: 'POST',
  url: 'http://localhost:3000/operation',
  data: JSON.stringify(data)
})