我开发了一个网络应用程序。 客户端 - Javascript/Typescript + AngularJS 服务器端-c#-asp.net web api 2 IIS Express 作为主机。
我注意到出现了一个奇怪的问题,POST 请求不止一次到达服务器。比如多次发送请求的一个场景,每次请求特定文件夹邮件发送3次。我还在“网络”选项卡中看到这些请求发送了三次。
public class mailsService extends ImailsService{
static instance : ImailsService;
// Dictionary of folder -> emails
public Folders;
public mailsService(){
var scope = this;
myInterval = setInterval(function(){
// Making this request until getting a successful response - waiting for server to go up
scope.webService.get("url to get my own place").success(data => {
scope.myLocation = data;
scope.isLocationInit = true;
getAllMails();
window.cleanInterval(myInterval);
})
}, 3000);
}
// This function happen on it's own when running the client code.
// The service is a singleton therefore this code runs only once.
public getAllMails() {
if (!this.isLocationInit)
return;
var scope = this;
scope.webService.get("url to get all folders").then(reponse => {
var folders = response.data;
for (var i = 1; i <= folders.length; i ++){
return scope.get("url to get the mails inside specific folder").then(initMails.bind(null, i));
}});
}
public initMails (folderId : number, response){
mailsService.instance.Folders[folderId].push(response.data);
}
}
public class webService extends IwebService {
public get(url : string){
return this.$http.get(url);
}
public post(url : string, data : any){
return this.$http.post(url, data);
}
}
// Server side:
// Cross-Origin requests
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MailsController : ApiController
{
private IMailsService _mailsService;
public MailsController(IMailsService service)
{
this._mailsService = service;
}
public IHttpActionResult GetAllFolders()
{
var result = _mailsService.GetAllFolders();
if (result == null)
return BadRequest("...");
return Ok(result);
}
public IHttpActionResult GetFolderEmails(int folderId)
{
var result = _mailsService.GetFolderEmails(folderId);
if (result == null)
return BadRequest("...");
return Ok(result);
}
}
尽管从客户端代码只调用了一次,但 Controller 拟合方法命中了两次甚至更多。
这是可配置的吗? IIS 奇怪的东西?我真的不知道从哪里开始寻找。
最佳答案
在 mailsService
中,您设置了一个间隔计时器,每 3 秒调用一次 Web 服务。有没有可能,当响应返回并且整个处理已经完成时,计时器已经滴答一两次并再次触发了程序?您可以通过将间隔更改为更短和更长的值来测试它,看看这是否会影响对服务器的调用次数。
降低风险的一种方法是在调用 getAllMails
之前,在成功回调函数的最开始调用 window.clearInterval
:
scope.webService.get("url to get my own place").success(data => {
window.clearInterval(myInterval);
scope.myLocation = data;
scope.isLocationInit = true;
getAllMails();
}
另一个解决方案是避免使用 setInterval
。您可以执行 scope.webService.get
并等待响应。如果出现错误,您将在延迟后再次调用该服务,使用 setTimeout
:
public mailsService() {
var scope = this;
(function callWebService () {
scope.webService.get("url to get my own place")
.success(data => {
scope.myLocation = data;
scope.isLocationInit = true;
getAllMails();
})
.error(data => {
setTimeout(callWebService, 3000);
});
})();
}
注意:我不熟悉Typescript,所以可能有更好的实现方式。
关于javascript - Http POST 请求多次到达服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39089415/