This article mainly describes the timeout items in $ HTTP (config) config:
$http({ timeout: number})
Value. It is calculated from the time the request is sent. The number of milliseconds has elapsed. If no response is received, an error is returned.
Demo:
HTML:
<!DOCTYPE html>
JS:
var jsonData = {name:"code_bunny"};var httpGet = angular.module(‘HttpGet‘,[]);httpGet.factory(‘getData‘,function($http,$q){ return function(){ var defer = $q.defer(); $http({ method:‘post‘, url:‘/api/user‘, data: jsonData, headers: {‘Authorization‘:‘code_bunny‘}, timeout: 1000 }).success(function(data,status,headers,config){ defer.resolve(data); }).error(function(data,status,headers,config){ defer.reject(data) }); return defer.promise }});httpGet.controller(‘dataController‘,function($scope,getData){ $scope.data = getData()});
Nodejs:
var express = require(‘express‘);var bodyParser = require(‘body-parser‘);var app = express();// parse application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({ extended: false }));// parse application/jsonapp.use(bodyParser.json());app.use(express.static(__dirname+‘‘));var data = "name=code_bunny&age=3";app.post(‘/api/user‘,function(req,res){ console.log(req.body); setTimeout(function(){ res.send(data) },2000)});app.listen(3000);
As shown in the code, we set the content to be returned after 2000 milliseconds in the background, but set the wait time to 1000 milliseconds in $ HTTP congif. Therefore, the data is not returned in the background, the request will be canceled:
* Note: timeout can only be configured in a single $ HTTP (). It cannot be configured through $ httpprovider. defaults. Timeout.
Full code path: https://github.com/OOP-Code-Bunny/angular/tree/master/OREILLY/18.4%20%24http (2)