I have about 70 of these in my angularjs code. About 65 of them send the authtoken variable through.
$http.post("/url", { name: $scope.name, authtoken:localStorage['authtoken']});
I remember seeing somewhere that it might be beneficial to make it so it passes authtoken as a default through all my $http.post calls so I don't have to type it in every time.
Is this a good idea? If so, does anyone know how I would accomplish it? Just looking for some insight and getting pushed in the right direction.
You can use Interceptors like this:
angular.module('app').config(function($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
request: function(req) {
if(req.method.toUpperCase() === 'POST') {
if(typeof req.data === 'object') {
req.data = req.data || {};// typeof Null is 'object' since the beginning of JavaScript
req.data['authtoken'] = localStorage['authtoken'];
} else {
req.data += '&authtoken='+localStorage['authtoken']
}
}
return req;
}
};
}
});
I hope this will help you.
Consider use of jQuery.ajaxSetup() here is API https://api.jquery.com/jQuery.ajaxSetup/
You can set up ajax global handler ajaxStar (https://api.jquery.com/ajaxStart/)
and modify the passed data by adding your authtoken.
Here is good article nearly about http://weblogs.asp.net/hajan/simplify-your-ajax-code-by-using-jquery-global-ajax-handlers-and-ajaxsetup-low-level-interface
Related
Is there a way to check to variable in localstorage ?
Storage {user: 'undefined', new: '{"_id":"61dd228336a3923d2286b994","email":"ahmadsa…","updatedAt":"2022-01-11T06:24:03.675Z","__v":0}', lscache-localhost:preview:v20180702-cacheexpiration: '27376332', lscache-localhost:preview:v20180702: '{}', length: 4}
And sometimes the data may be on the user property base on user login . below is the login that returns the property in user
Storage {user: '{"team_members":{"memberFullname1":"memberFullname…","updatedAt":"2022-01-10T01:43:30.288Z","__v":0}', new: 'null', length: 2}
How can I create condition that checks both property an only return the ones that contain a value ?
Base on user log in, I can only use one variable either new or user. Is there not away I can check two conditions before rendering my data from localStorage ?
This is the Method I try. But it only check the first condition even though the second condition is there, it return. Uncaught error in Json.parse()
if (typeof Storage !== "undefined") {
if (localStorage.getItem("new")) {
setUser(JSON.parse(window.localStorage.getItem("new")));
} else if (localStorage.getItem("user")) {
setUser(JSON.parse(window.localStorage.getItem("user")));
}
return;
}
Is there a way I can check both condition ? Your time is really appreciated. please I am a brother need..
And lastly how can I prevent re-rendering of the state
If user undefined, do new, if that's undefined, do {}, parse.
if (typeof Storage !== "undefined") {
setUser(JSON.parse(localStorage.user || localStorage.new || '{}'));
}
Though, if you look at new, it's not the same as user, in terms of structure so you might want to fix that else they are not the same thing.
I found these code allows me to check both conditions and it didn't return error like the previous one.
useEffect(() => {
const fetchStates = async () => {
const result = await axios(
"https://nigerian-states-info.herokuapp.com/api/v1/states"
);
setStates(result.data.data);
};
fetchStates();
if (localStorage.user === "undefined") {
return setUser(JSON.parse(localStorage.getItem("new")));
} else if (localStorage.new === "undefined") {
return setUser(JSON.parse(localStorage.getItem("user")));
}
}, [formData, user]);
Finally after a bunch of try and error, I finally arrived at that part. I want to sent my sincere appreciation to all those who took there time and review my issues even those that did not get to answer. I send A BIG THANK YOU especially to lawrence cherone your idea was a great helpful in shaping my thought. thank you all
I am new in node js. I am getting a typeerror while using .get function. The error is
TypeError: item.get is not a function
Code --
query.lean().exec(function (err, data)
{
JSON.stringify(data);
callback(null,data,count);
});
function(data,count,callback)
{
//...some code
callback(null,[count,data]);
}
function(docs, callback){
console.log(docs[1]);
async.each(docs[1],function(item,cb) {
if (typeof(item.video.path)!="undefined") {
item.players.cover = config.general+ item.video.path;
}
});
}
I did console.log(docs[1]) and the video.path exist within the json object.Before using lean() this set and get was working but not now.
Any help is highly appreciated. Thanks in advance.
If item is an object de-serialised from JSON, then there's no way it has any methods or functions.
I suspect you just want to set a property on the object. Something like
if (typeof item.video.path !== 'undefined') {
// ensure item.players is an object first
item.players = item.players || {}
// now set the value
item.players.cover = config.general + item.video.path
}
Hi trying to get a signUrl from S3, for some reason making the call with % isn't parse correctly by my code. I get a 404 not found.
This is the ajax request:
https://stage.musicmarkers.com/website/api/admin/get-signed-url/thumbnail/magazine%2F2BE.gif/image%2Fgif
My API:
app.get('/website/api/admin/get-signed-url/thumbnail/:key/:type', auth.getMember, directives.noCache, getThumbnailSingedUrl);
My function:
function getThumbnailSingedUrl(req, res) {
if (!isAdmin(req, res)) {
return;
}
var key = req.params.key || '';
var type = req.params.type || '';
ThumbnailBucketFacade.getSignedUrl(
'putObject',
key,
type,
function onGotSignedUrl(error, result) {
if (error) {
RestResponse.serverError(res, error);
} else {
RestResponse.ok(res, result);
}
}
);
}
Making the call in a dev environment works.
Making the call without % environment works.
Same code exactly in a different project works.
Any ideas?
I believe what you have is encoded URI. So you need to decode it before using it:
const key = req.params.key && decodeURIComponent(req.params.key) || '';
const type = req.params.type && decodeURIComponent(req.params.type) || '';
More on decoreURIComponent here.
This is also backward compatible, so you don't have to worry that a plain string will get mangled.
So eventually it was a configuration issue at 'nginx', the 'nginx' router
was configured to add '/' at the end of the site name. That made all the
other slashes scrambled and ultimately to the call not to be recognise.
Thank's for those helping.
We are having a little problem with a functional test with casper.js.
We request the same resource twice, first with the GET and then with POST method.
Now when waiting for the second resource (POST) it matches the first resource and directly goes to the "then" function.
We would like to be able to check for the HTTP method in the "test" function, that way we can identify the resource properly. For now we use the status code (res.status), but that doesn't solve our problem fully, we really need the http method.
// create new email
this.click(xPath('//div[#id="tab-content"]//a[#class="button create"]'));
// GET
this.waitForResource('/some/resource',
function then() {
this.test.assertExists(xPath('//form[#id="email_edit_form"]'), 'Email edit form is there');
this.fill('form#email_edit_form', {
'email_entity[email]': 'test.bruce#im.com',
'email_entity[isMain]': 1
}, true);
// POST
this.waitForResource(
function test(res) {
return res.url.search('/some/resource') !== -1 && res.status === 201;
},
function then() {
this.test.assert(true, 'Email creation worked.');
},
function timeout() {
this.test.fail('Email creation did not work.');
}
);
},
function timeout() {
this.test.fail('Email adress creation form has not been loaded');
});
Or maybe there is a better way to test this scenario? Although since this is a functional test we need to keep all those steps in one test.
You can try to alter the form action url to add some query string, therefore generating a new resource appended to the stack. Could be done this way:
casper.thenEvaluate(function() {
var form = __utils__.findOne('#email_edit_form');
form.setAttribute('action', form.getAttribute('action') + '?plop');
});
That's a hack though, and functional testing should never be achieved that way. Let's hope more information will be added to the response objects in the future.
The res parameter that is passed to the test function has an ID. I created a helper that tests against this ID and blacklists it, so the same resource won't get accepted a second time.
var blackListedResourceIds = [],
testUniqueResource = function (resourceUrl, statusCode) {
return function (res) {
// check if resource was already loaded
var resourceFound = res.url.search(resourceUrl) !== -1;
// check statuscode
if (statusCode !== undefined) {
resourceFound = resourceFound && res.status === statusCode;
}
// check blacklisting
if (!resourceFound || blackListedResourceIds[res.id] !== undefined) {
return false;
} else {
blackListedResourceIds[res.id] = true;
return true;
}
};
};
Load when the browser is open
Thats my previous question related to this topic.
My problem is that the server api i use has added a new item to the list and as i stated in the previous question im not very skilled with API's or jQuery, therefore i would like to know what can you recomend me to read about this and also pratical solutions. I need to make it so the field that the js uses is only {"name":"Arthas","slug":"arthas","build":"12340","status":1} and not the rest.
Many thanks in advance.
This is the api -> http://api.neverendless-wow.com/server-status
{"servers":[{"name":"Arthas","slug":"arthas","build":"12340","status":1},{"name":"Deathwing","slug":"deathwing","build":"13623","status":1}],"alerts":[]}
This is my current js
function checkStatus()
{
jQuery.getJSON("http://api.neverendless-wow.com/server-status",function(data){
if (data.status == '1') {jQuery('#ServStat').addClass('online').removeClass('offline').attr('label','Online');}
else {jQuery('#ServStat').addClass('offline').removeClass('online').attr('label','Offline');}});
}
checkStatus();
{
setInterval(changeState, 300000)
}
You need to use data as array (data[0]) and hence your code will be as follows:
function checkStatus()
{
jQuery.getJSON("http://api.neverendless-wow.com/server-status",function(data){
if (data.servers[0].status == '1') {
jQuery('#ServStat').addClass('online').removeClass('offline').attr('label','Online');
}
else {
jQuery('#ServStat').addClass('offline').removeClass('online').attr('label','Offline');
}
});
}
checkStatus();
{
setInterval(changeState, 300000)
}
I would probably go with something like this:
// check server status
function checkStatus()
{
$.getJSON(server_url, function(data) {
// reset
var mode = "Offline";
$('.status').removeClass('online').addClass('offline');
// is available?
if (data !== null && data.servers !== null && data.servers[0].status === 1) {
mode = "Online";
$('.status').removeClass('offline').addClass('online');
}
// Extract data from received JSON string is exists
extractData(data);
// set needed attributes
$('.status')
.attr('label', mode)
.text('Servers are ' + mode);
});
}
Live demo available on JsBin