Angularjs and Nodejs express - express

I'm trying to upload images through angularjs (client side) and Nodejs express (server side). I perfer not to use forms because my company does not work with it.
this is part of my controller-
$scope.uploadPhotoToServer = function () {
console.log('will upload to album ' + this.albumName + ' file ' + this.userPhoto);
var fd = new FormData();
//Take the first selected file
fd.append("file", this.userPhoto);
fd.append("album", this.albumName);
$http.post('/upload', fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
});
}]);
I wish if you could explain to me how this works and how I could continue
Thanks in advance :)

I'm not sure what you want to know, or what part you don't understand, but this basically just creates a $scope member function that adds the userPhoto and albumName to the FormData object (fd), which represents the form.The function then sends that object to the server using $http. You can think of the $http as a typical ajax command that just sends data to the server. (It actually uses the same XMLhttpRequest object that ajax does.
if you need it, here is a reference to the FormData() being used:
https://developer.mozilla.org/en-US/docs/Web/API/FormData

Related

fetching inside express server - fetch is not defined

I am trying to get a long lived access token from facebook... according to the documentation, I need to fetch from the server side for security. If I fetch from the client side it works fine - but I should follow the guidelines.. Here is what I am doing - can you tell me why I get the server side error "Reference error: fetch is not defined"?
First I created a route from the front end to request the long lived token. To get the long lived token I need to use the short lived token so I send the short lived token in the req params. The variable userAccessTokenShort is valid and defined.
const newLongLivedUserAccessToken = await fetch(`/api/autoquotegenerators/longLivedUserToken/${userAccessTokenShort}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json; charset=UTF-8",
},
})
const newLongUserTokenRes = await newLongLivedUserAccessToken.json()
console.log(newLongUserTokenRes)
Then, on my express server, I made a route that handles the fetch request to the Facebook Graph API. This is where I get the reference error.
//Get Long Lived User Access Token on Backend /express route
router.get('/longLivedUserToken/:shortLived', (req, res) => {
try {
const getLongToken = fetch(`https://graph.facebook.com/v7.0/oauth/access_token?grant_type=fb_exchange_token&client_id=#############&client_secret=################&fb_exchange_token=${req.params.shortLived}`)
.then(token => res.send(token))
} catch (error) {
console.log(error)
}
})
If all goes well, the new token should be sent back to the client.
Thanks for your help!
There is no fetch() function built into node.js. If you want something that looks pretty much like fetch() in the browser, you can look at the node-fetch module in NPM.
Or, there are lots of modules you can choose from in node.js. My favorite is got().
FYI, the built-in interface for fetching http requests is http.request() or http.get(), but they are lower level and require more lines of code to do something simple than any of the above named modules.

Axios - Remove headers Authorization in 1 call only

How can I remove the axios.defaults.headers.common.Authorization only in 1 call?
I'm setting the default for all the calls to my domain but I have 1 call that I make on another domain and if the token is passed the call gives me an error, when there's no default Auth token saved everything works fine.
So what I'm trying to do is not pass the Auth in that specific call
I tried this but it doesn't work
loadApiCoins({ commit }) {
Vue.axios({
method: 'get',
url: 'https://api.coinmarketcap.com/v1/ticker/',
headers: {
'Authorization': '',
},
}).then(...)
},
I also tried auth: {...} but that doesn't work either.
What's the solution?
Thanks
Try the following
delete axios.defaults.headers.common["Authorization"];
// or which ever header you have to remove
To send a request without:
Modifying global axios defaults
Creating a new axios instance
Change your request similarly to this:
axios.get('http://example.com', {transformRequest: (data, headers) => {
delete headers.common['Authorization'];
return data;
}
});
The answer I was looking for was posted in the comments of Apurva jain's answer, but hasn't been made an individual answer, so I've posted it separately for easy reference :)
if you already have a default 'Authorization' for all requests
you can create an instance for that specific request
var instance = axios.create();
delete instance.defaults.headers.common['Authorization'];
instance.get("http://api.com");
delete axios.defaults.headers.common["Authorization"];
will solve the problem. But remember to add the authorization header back.
I got the same issue trying to query S3 with my web-service auth token. Fixed it with this.
axios.get("http://api.com", {
headers:{ Authorization:""}
});
You can change the default headers to an empty string, this won't affect the common default headers. Though not entirely sure if all web services will ignore the empty string header.
A simple solution is to remove all common header from a new axios instance:
const awsAxios = axios.create({
transformRequest: (data, headers) => {
// Remove all shared headers
delete headers.common;
// or just the auth header
delete headers.common.Authorization;
}
});
delete request.defaults.headers.common.Authorization
That request should be return of a $axios.create()
To extend on #phantomraa's answer, you might want to use
this.$axios.$get(
url, {
// modify auth header for current request only
transformRequest: (data, headers) => {
// prevent the header from being added by default
delete headers.common['Authorization'];
// some libraries might set it directly as well, e.g. nuxtjs/auth
delete headers['Authorization'];
return data;
}
})
Sorry, need a bit more rep to just comment.
According to the latest axios Request Config documentation we can use transformRequest:
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
An example:
axiosInstance.post('/api/auth-token', { email, password }, {
transformRequest: [
(data, headers) => {
delete headers.common['Authorization'];
return JSON.stringify(data);
},
],
});
Please note the call to JSON.stringify as mentioned in the documentation, you need to return a Buffer, ArrayBuffer, FormData or Stream.
const mynewinstance = axios.create();
mynewinstance.defaults.headers.common = {};
const output = await mynewinstance.get(`https://google.com`);
delete axios.defaults.headers.common["language"];

Firebase + Ionic Framework: Chat notifications

SO I am wondering if its possible to implement some sort of notifications with Firebase and Ionic Framework, which I am using to create app. Can I stick with Firebase only, or do I need to get some other service, such as for example Parse?
Thanks!
EDIT:
I got Parse working - awesome. THe only thing that doesnt really work for me is the following code:
function sendNotification(deviceToken, content){
console.log('targetDevice is: ' + deviceToken);
console.log('content is:' + content);
var notificationEndpoint = AY_Parse.parseEndpoint + "/1/push";
var headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': AY_Parse.parseApplicationId,
'X-Parse-REST-API-Key': AY_Parse.parseRestApiKey
};
var pushNotification = $resource(notificationEndpoint, {},
{
'save': {
method: 'PUT',
headers: headers
}
});
var registerNotification = new pushNotification();
registerNotification.deviceToken = deviceToken;
registerNotification.data = {alert: content};
console.log(registerNotification);
console.log(angular.toJson(registerNotification));
return registerNotification.$save;
}
It should send Push notificaiton to the targeted device, however it does nothing..
ANSWER:
Ok, the problem was with the following line:
registerNotification.deviceToken = deviceToken;
Changed to:
registerNotification.where= {deviceToken: deviceToken};
I'm unsure about Firebase but using Parse was easy to follow and understand, I managed to get everything working perfectly with the ngCordova Push Notifications.
https://parse.com/products/push
http://ngcordova.com/docs/plugins/pushNotifications/
https://www.parse.com/tutorials/ios-push-notifications
I hope these help.

How to consume WCF soap web service in node.js

I tried lot of examples available in the net using node module wcf.js. But could not get any appropriate result. I'm using the below url
https://webservice.kareo.com/services/soap/2.1/KareoServices.svc?wsdl
Any one who can explain me with the help of code will be really helpful. I want to know how to access the wsdl in node.js
Thanks.
Please have a look at wcf.js
In short you can follow these steps:
npm install wcf.js
Write your code like this:
code
var Proxy = require('wcf.js').Proxy;
var BasicHttpBinding = require('wcf.js').BasicHttpBinding;
var binding = new BasicHttpBinding();
//Ensure the proxy variable created below has a working wsdl link that actually loads wsdl
var proxy = new Proxy(binding, "http://YourHost/YourService.svc?wsdl");
/*Ensure your message below looks like a valid working SOAP UI request*/
var message = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:sil='http://YourNamespace'>" +
"<soapenv:Header/>" +
"<soapenv:Body>" +
"<sil:YourMethod>" +
"<sil:YourParameter1>83015348-b9dc-41e5-afe2-85e19d3703f9</sil:YourParameter1>" +
"<sil:YourParameter2>IMUT</sil:YourParameter2>" +
"</sil:YourMethod>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
/*The message that you created above, ensure it works properly in SOAP UI rather copy a working request from SOAP UI*/
/*proxy.send's second argument is the soap action; you can find the soap action in your wsdl*/
proxy.send(message, "http://YourNamespace/IYourService/YourMethod", function (response, ctx) {
console.log(response);
/*Your response is in xml and which can either be used as it is of you can parse it to JSON etc.....*/
});
You don't have that many options.
You'll probably want to use one of:
node-soap
douche
soapjs
i tried node-soap to get INR USD rate with following code.
app.get('/getcurr', function(req, res) {
var soap = require('soap');
var args = {FromCurrency: 'USD', ToCurrency: 'INR'};
var url = "http://www.webservicex.net/CurrencyConvertor.asmx?WSDL";
soap.createClient(url, function(err, client) {
client.ConversionRate(args, function(err, result) {
console.log(result);
});
});
});
Code Project has got a neat sample which uses wcf.js for which api's are wcf like so no need to learn new paradigm.
I think that an alternative would be to:
use a tool such as SoapUI to record input and output xml messages
use node request to form input xml message to send (POST) the request to the web service (note that standard javascript templating mechanisms such as ejs or mustache could help you here) and finally
use an XML parser to deserialize response data to JavaScript objects
Yes, this is a rather dirty and low level approach but it should work without problems
You'll probably want to use one of:
node-soap
douche
soapjs
Aslo, there's an existing question.
In my case, I used https://www.npmjs.com/package/soap. By default forceSoap12Headers option was set to false which prevented node-soap to generate correct soap message according to SOAP 1.2. Check for more details: I am confused about SOAP namespaces. After I set it to true, I was able to make a call to .NET WCF service. Here is a TypeScript code snipper that worked for me.
import * as soap from 'soap';
import { IOptions } from 'soap';
// ...
const url = 'https://www.your-domain.com/stock.svc?wsdl';
const opt: IOptions = {
forceSoap12Headers: true,
};
soap.createClient(url, opt, (err, client: soap.Client) => {
if (err) {
throw err;
}
const wsSecurityOptions = {
hasTimeStamp: false,
};
const wsSecurity = new soap.WSSecurity('username', 'password', wsSecurityOptions);
client.setSecurity(wsSecurity);
client.addSoapHeader({ Action: 'http://tempuri.org/API/GetStockDetail' }, undefined, 'wsa', 'http://www.w3.org/2005/08/addressing');
client.addSoapHeader({ To: 'https://www.your-domain.com/stock.svc' }, undefined, 'wsa', 'http://www.w3.org/2005/08/addressing');
const args = {
symbol: 'GOOG',
};
client.GetStockDetail(
args,
(requestErr, result) => {
if (requestErr) {
throw requestErr;
}
console.log(result);
},
);
});
Here couple links to the documentation of node-soap usage:
https://github.com/vpulim/node-soap/tree/master/test
https://github.com/vpulim/node-soap

Using Node JS to proxy http and modify response

I'm trying to write a front end to an API service with Node JS.
I'd like to be able to have a user point their browser at my node server and make a request. The node script would modify the input to the request, call the api service, then modify the output and pass back to the user.
I like the solution here (with Express JS and node-http-proxy) as it passes the cookies and headers directly from the user through my site to the api server.
proxy request in node.js / express
I see how to modify the input to the request, but i can't figure out how to modify the response. Any suggestions?
transformer-proxy could be useful here. I'm the author of this plugin and I'm answering here because I found this page when looking for the same question and wasn't satisfied with harmon as I don't want to manipulate HTML.
Maybe someone else is looking for this and finds it useful.
Harmon is designed to plug into node-http-proxy https://github.com/No9/harmon
It uses trumpet and so is stream based to work around any buffering problems.
It uses an element and attribute selector to enable manipulation of a response.
This can be used to modify output response.
See here: https://github.com/nodejitsu/node-http-proxy/issues/382#issuecomment-14895039
http-proxy-interceptor is a middleware I wrote for this very purpose. It allows you to modify the http response using one or more transform streams. There are tons of stream-based packages available (like trumpet, which harmon uses), and by using streams you can avoid buffering the entire response.
var httpProxy = require('http-proxy');
var modifyResponse = require('http-proxy-response-rewrite');
var proxy = httpProxy.createServer({
target:'target server IP here',
});
proxy.listen(8001);
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
proxy.on('proxyRes', function (proxyRes, req, res) {
modifyResponse(res, proxyRes.headers['content-encoding'], function (body) {
if (body && (body.indexOf("<process-order-response>")!= -1)) {
var beforeTag = "</receipt-text>"; //tag after which u can add data to
// response
var beforeTagBody = body.substring(0,(body.indexOf(beforeTag) + beforeTag.length));
var requiredXml = " <ga-loyalty-rewards>\n"+
"<previousBalance>0</previousBalance>\n"+
"<availableBalance>0</availableBalance>\n"+
"<accuruedAmount>0</accuruedAmount>\n"+
"<redeemedAmount>0</redeemedAmount>\n"+
"</ga-loyalty-rewards>";
var afterTagBody = body.substring(body.indexOf(beforeTag)+ beforeTag.length)+
var res = [];
res.push(beforeTagBody, requiredXml, afterTagBody);
console.log(res.join(""));
return res.join("");
}
return body;
});
});