Angular 4 HTTP请求中有没有避免使用&符号的选项?

huangapple go评论91阅读模式
英文:

Is there any option for avoid the & symbol in Angular 4 HTTP request?

问题

我使用HTTP请求将数据存储在我的数据库中。为此,我只是使用了以下代码。

const form = '&inputdata=' + myinput + '&rf_date=' + rf_date;
return this.http.post(this.rootUrl, form, {headers : this.reqHeader});

在这里,inputdata = "Files & Folders"。当我运行这个代码时,只有"Files"被存储在我的数据库中。因为&符号是分隔符,所以"& Folders"没有被存储。是否有办法解决这个问题在Angular 4中?

英文:

Am using HTTP request to store the data in my database. For that, I just used the following code.

    const form = '&inputdata=' + myinput + '&rf_date=' + rf_date;
    return this.http.post(this.rootUrl, form, {headers : this.reqHeader});

here, inputdata = "Files & Folders". When am running this only "Files" storing in my DB. "& Folders" is not stored. Because of the '&' delimiter.

So, is there any option to resolve this issue in Angular 4?

答案1

得分: 2

你可以(也应该)使用请求的主体部分发送到服务器。官方 Angular HTTP 客户端文档

你可以像这样向后端发送一个 JSON 对象:

const form = {inputdata: myinput, rf_date: rf_date};
return this.http.post(this.rootUrl, form, {headers : this.reqHeader});

在设计 API 时,最好使用标准格式如 JSON。根据你选择的 API,将 JSON 对象映射/反序列化到后端结构应该相对容易。

英文:

You can (and should) use the body of the request to send to the server. Official http client angular documentation

You can send a json object to your backend like this:

const form = {inputdata: myinput, rf_date: rf_date};
return this.http.post(this.rootUrl, form, {headers : this.reqHeader});

Prefer standard formats like json when you are designing your api. Depending on the api of your choice, it should be fairly easy to map/deserialize the json object to your backend structure.

答案2

得分: 0

你可以使用 encodeURIComponent(val) 来对你的变量进行编码(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent)

例如:

const form = '&inputdata=' + encodeURIComponent(myinput) + '&rf_date=' + rf_date;
return this.http.post(this.rootUrl, form, {headers : this.reqHeader});
英文:

You can use encodeURIComponent(val) to encode your variables (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent)

i.e.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  const form = &#39;&amp;inputdata=&#39; + encodeURIComponent(myinput) + &#39;&amp;rf_date=&#39; + rf_date;
  return this.http.post(this.rootUrl, form, {headers : this.reqHeader});

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月3日 17:27:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定