SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd. index.html - angularjs

I am using Visual studio 2015 and ionic and i have been able to build for windows phone 8.1. I created a login page that is to query a php on a different server but i get a problem like this SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
index.html
error. My code trying to make a request is
var login = function(name, pw) {
return $q(function(resolve, reject) {
$http.post('http://192.167.180.1//logn/sear.php',{ 'pin': pw }).then(
function(result) {
// No result here..
var re=result.data.split(",");
console.log(re[3]);
if ((re[0] == 0 )) {
// Make a request and receive your auth token from your server
storeUserCredentials(re[2]);
useCredentials(re[1]+" "+re[3]+" "+re[4]);
console.log(LOCAL_TOKEN_KEY);
resolve('Login success.');
} else if(result.data == 1) {
reject('Login Failed.');
}
}, function(err) {
// $scope.response = err.records;
console.log("error");
});
});
};

When you are facing this error while building a Win 8 Phone App, you might want to add private network capability to app manifest.
Credits for the guy who helped me out: https://sonyarouje.com/tag/network-error/
- there you'll find step-by-step instruction how to do it.
There is also another answer how to do it on SO:
WinJS.xhr: Network Error 0x2efd, Could not complete the operation due to error 00002efd

Related

Cannot get Cypress test to work in React with Okta

I am trying to test my React (v16.10.2) application with Cypress (v4.5.0). Our application is using Okta for authentication (with the client #okta/okta-react 1.3.1).
I can use my app from the browser without any issues. The first time I login, I get the Okta login screen. I enter my user ID and password, and the react client calls the authn endpoint with my creds, and then calls the authorization endpoint to get the token. I am then taken to the first screen of our application.
When I try to login in my Cypress test, my user ID and password are entered into the login screen, the authn endpoint is called successfully, but the authorization endpoint returns a 403 error. Unfortunately, there is no other info about why I am getting the 403.
I have compared the authorization requests between the one that works in the browser, and the one that doesn't work from Cypress. The only real difference I see is that the working browser request has an origin header, whereas the failing one does not.
Question #1: Could the missing origin header be the cause of my problem?
In order to avoid a bunch of CORS and cross-site issues, I had to install a couple Chrome extensions (ignore-x-frame-headers and Access-Control-Allow-Origin-master). I am implementing them in the following code in cypress/plugins/index.js:
module.exports = (on, config) => {
on('before:browser:launch', (browser = {}, launchOptions) => {
// The following code comes from https://medium.com/#you54f/configuring-cypress-to-work-with-iframes-cross-origin-sites-afff5efcf61f
// We were getting cross-origin errors when trying to run the tests.
if (browser.name === 'chrome') {
const ignoreXFrameHeadersExtension = path.join(__dirname, '../extensions/ignore-x-frame-headers');
launchOptions.args.push(`--load-extension=${ignoreXFrameHeadersExtension}`);
const accessControlAllowOriginMasterExtension = path.join(__dirname, '../extensions/Access-Control-Allow-Origin-master');
launchOptions.args.push(`--load-extension=${accessControlAllowOriginMasterExtension}`);
launchOptions.args.push("--disable-features=CrossSiteDocumentBlockingIfIsolating,CrossSiteDocumentBlockingAlways,IsolateOrigins,site-per-process");
launchOptions.args.push('--disable-site-isolation-trials');
launchOptions.args.push('--reduce-security-for-testing');
launchOptions.args.push('--out-of-blink-cors');
}
if (browser.name === 'electron') {
launchOptions.preferences.webPreferences.webSecurity = false;
}
return launchOptions;
});
I also added the following to cypress.json:
{
"chromeWebSecurity": false
}
Here is my cypress test:
describe('Order Lookup Test', () => {
const UI_URL: string = 'http://localhost:3000/';
const ORDER_NUMBER: string = '10307906234';
beforeEach(() => {
Cypress.config('requestTimeout', 50000);
cy.visit(UI_URL);
cy.get('#okta-signin-username', {timeout: 10000}).type('xxxxxxxx');
cy.get('#okta-signin-password', {timeout: 10000}).type('xxxxxxxx');
cy.get('#okta-signin-submit', {timeout: 10000}).click();
})
it('should return an order', () => {
cy.get('.number-input', {timeout: 10000}).type(ORDER_NUMBER);
cy.get('.order-lookup-buttons-search-valid').should('be.visible').click();
})
})
Does anyone have any idea what might be going on? What other information should I be including in order to help narrow this down?

Handle Error when the server is off in react js (TypeError Failed to fetch)

I need to show error in a dialog stating the server has stopped whenever the server crashes or server gets shut down.
I as console log my error in request as below:
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON).
catch(error => {
console.log("error",error)
throw error;
});
}
the console is :
TypeError Failed to fetch
Can someone help me with this?
you can use navigator in you code in order to check if user is offline nor user can't connect to your WebService like below:
//if there was a problem with server
if(navigator && navigator.onLine) {
throw {
code: 'SERVER_CONNECTION_PROBLEM',
message: 'Server connection failure...'
}
} else { // if there is a problem with internet
throw {
code: 'INTERNET_CONNECTION_ERROR',
message: 'there is a problem with your INTERNET, god damn it...'
}
}
You can check error status e.g. error.status and do
if(error.statusCode === 503){ // or status code which your server send
// do something
}
There is library called react-offline.
which used in detect your network is in work or not.
After proper implementation it should be work, it shows offline page which you created when your network goes down...
link is here : https://openbase.com/js/react-offline/documentation
[Click here for documentation][1]
[1]: https://openbase.com/js/react-offline/documentation
code example :
<Offline
render={() => {
return (
<div>"I take precedence over any function as child component."</div>
);
}}
>
{() => {
return <div>"I will not render."</div>;
}}
</Offline>

Twilio & NodeJS: can't find and delete Media instances/resources

I'm using Twilio's NodeJS module & API to send out MMS messages with images attached (from a remote URL), and I want to delete the Media instances that get created on Twilio servers as soon as I send out the messages.
My messages send out correctly, and in the callback, I'm trying to 1) list media instances for the current message, then 2) loop through those instances and delete. The problem is that the mediaList array that comes back from the API for a current message is always empty.
Here's my code:
twilio_client.messages.create({
body: "Thanks for taking a photo. Here it is!",
to: req.query.From,
from: TWILIO_SHORTCODE,
mediaUrl: photo_URL,
statusCallback: STATUS_CALLBACK_URL
}, function(error, message) {
if (!error) {
twilio_client.messages(message.sid).media.list(function(err, data) {
console.log(data);
// The correct object comes back as 'data' here per the API
// but the mediaList array is empty
}
console.log('Message sent via Twilio.');
res.status(200).send('');
} else {
console.log('Could not send message via Twilio: ');
console.log(error);
res.status(500).send('');
}
});
So, it turns out that trying to get the media list at the point I was trying to doesn't work because the media instances didn't exist yet.
I have a separate little app running at the statusCallback (I supply a URL via a constant in the code above, STATUS_CALLBACK_URL), that until now, just checked to see if a message I tried to MMS to a user wasn't handled properly by Twilio, and alerted the user to a problem via SMS. So, I added a check in that same app to see if the message was actually 'sent' to the user, and then checked for and deleted the media instance(s) associated with the message at that point, and it works fine. Here's my code:
// issue message to user if there's a problem with Twilio getting the photo
if (req.body.SmsStatus === 'undelivered' || req.body.SmsStatus === 'failed') {
twilio_client.messages.create({
body: "We're sorry, but we couldn't process your photo. Please try again.",
to: req.body.To,
from: TWILIO_SHORTCODE
}, function(error, message) {
if (!error) {
console.log('Processing error message sent via Twilio.');
res.send(200,'');
} else {
console.log('Could not send processing error message via Twilio: ' + error);
res.send(500);
}
});
}
// delete media instance from Twilio servers
if (req.body.SmsStatus === 'sent') {
twilio_client.messages(req.body.MessageSid).media.list(function(err, data) {
if (data.media_list.length > 0) {
data.media_list.forEach(function(mediaElement) {
twilio_client.media(mediaElement.sid).delete;
console.log("Twilio media instance deleted");
});
}
});
}

angular ngressource issue TypeError: Cannot read property 'get' of undefined

I'm new to angular and I'm trying to to create a service to register and login users using a spring rest controller, below is the Angular code to retrive Json data
.factory('accountService', function($resource) {
var service = {};
service.register = function(account, success, failure) {
var Account = $resource("/mywebapp/rest/account");
Account.save({}, account, success, failure);
};
service.userExists = function(account, success, failure) {
var Account = $resource("/mywebapp/rest/account");
var data = account.get({email:'email'}, function() {
var accounts = data.accounts;
if(accounts.length !== 0) {
success(accounts[0]);
} else {
failure();
}
},
failure);
};
return service;
})
the problem is that i'm getting two type of error message in chrome and FireFox when trying to connect (service.userExists):
TypeError: Cannot read property 'get' of undefined
at Object.service.userExists (http://localhost:8080/mywebapp/resources/js/account.js:42:27)
at h.$scope.login (http://localhost:8080/mywebapp/resources/js/account.js:56:24)
at http://localhost:8080/mywebapp/resources/lib/angular/angular.js:178:68
at f (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:195:177)
at h.$eval (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:113:32)
at h.$apply (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:113:310)
at HTMLFormElement.<anonymous> (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:195:229)
at http://localhost:8080/mywebapp/resources/lib/angular/angular.js:31:225
at r (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:7:290)
at HTMLFormElement.c (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:31:207)
and in firefox:
"Error: account is undefined
service.userExists#http://localhost:8080/mywebapp/resources/js/account.js:42:13
$scope.login#http://localhost:8080/mywebapp/resources/js/account.js:56:1
gb.prototype.functionCall/<#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:178:66
jc[c]</<.compile/</</f#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:195:177
Yd/this.$get</h.prototype.$eval#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:113:28
Yd/this.$get</h.prototype.$apply#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:113:305
jc[c]</<.compile/</<#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:195:227
ne/c/<#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:31:223
r#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:7:288
ne/c#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:31:207
i'm also getting this error when trying to register a new account:
[HTTP/1.1 415 Type de Support Non Supporté 98ms]
Would you please help me.
ng-resource seems to never receive the account parameter which means the get request is not returning the account. Check the network tools to see what the userExists request is returning from the server.
The message your are receiving for the register could be a hint, I would say it means the API doesn't support your type of client, maybe you're using an old browser or a the server API is very old.

How to alert the user when there's no internet connection

I need to alert the user with the following conditions;
Request timed out
No internet connection
Unable to reach the server
Here's the code; How to capture the following conditions when occurred and alert the user ?
failure: function (response) {
var text = response.responseText;
console.log("FAILED");
},success: function (response) {
var text = response.responseText;
console.log("SUCCESS");
}
I tried the following code to check if the internet is reachable, but it didn't work
var networkState = navigator.network.connection.type
alert(states[networkState]);
if (networkState == Connection.NONE){
alert('No internet ');
};
UPDATE **
I added the following in my index.html, but, when i disable WIFI, i don't see the alert popping.
<script>
function onDeviceReady() {
document.addEventListener("offline", function() {
alert("No internet connection");
}, false);
}
</script>
The best thing to do is to listen to the "offline" event. When you get the offline event you can warn your user and take whatever steps necessary to save data, etc.
For instance, your "deviceready" callback:
document.addEventListener("offline", function() {
alert("No internet connection");
}, false);
This code should work for most all versions of PhoneGap. It's been in since at least the 1.0 release.
Exactly as Simon said, you can use
document.addEventListener("offline", youCallbackFn, false);
or you can interrogate the boolean property
navigator.onLine
(Should return true or false)
However, this technique will tell you whether device is connected. The caveat is such that device can be connected to WiFi, but the router might be offline. In that case, use a polling mechanism, like timely Ext.Ajax.request with lower timeouts. Timeout expired = offline.
You can use PhoneGap's NETWORK API
The network object gives access to the device's cellular and wifi connection information.
You can test it in the following way,
function onDeviceReady() {
navigator.network.isReachable("phonegap.com", reachableCallback, {});
}
// Check network status
//
function reachableCallback(reachability) {
// There is no consistency on the format of reachability
var networkState = reachability.code || reachability;
var states = {};
states[NetworkStatus.NOT_REACHABLE] = 'No network connection';
states[NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK] = 'Carrier data connection';
states[NetworkStatus.REACHABLE_VIA_WIFI_NETWORK] = 'WiFi connection';
alert('Connection type: ' + states[networkState]);
}
You can add 'Ext.device.Connection' in app.js of your application. And check your device is online or offline using code:
if (Ext.device.Connection.isOnline()) {
alert('Connected to internet');
}
else{
alert('You are not connected to internet');
}
Just Embed this in your tag
<body onoffline="alert('PLEASE CHECK YOUR INTERNET SETTING');">

Resources