英文:
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 = '&inputdata=' + encodeURIComponent(myinput) + '&rf_date=' + rf_date;
return this.http.post(this.rootUrl, form, {headers : this.reqHeader});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论