How to send auth token in feathersjs via post to rest service? - feathersjs

I am working through learning feathers and I am trying to send some data to a service I created. It works fine when I use it without any authorization. When I add authorization I can send the JWT token manually with postman. However when I send a post I am not sure how to send the token in the header or the best way to handle this. The example I have found uses socket.io. Is there a way to do this with a simple post?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0">
<title>Feathers Chat</title>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="//cdn.rawgit.com/feathersjs/feathers-chat/v0.1.0/public/base.css">
<link rel="stylesheet" href="//cdn.rawgit.com/feathersjs/feathers-chat/v0.1.0/public/chat.css">
</head>
<body>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="//unpkg.com/feathers-client#^1.0.0/dist/feathers.js"></script>
<script type="text/javascript">
var host = 'http://localhost:3030';
// Set up Feathers client side
var app = feathers()
.configure(feathers.rest(host).jquery(jQuery))
.configure(feathers.hooks())
.configure(feathers.authentication({ storage: window.localStorage }));
// authenticate using your JWT that was passed in the short lived cookie
app.authenticate().then(function(result){
console.log('Authenticated!', result);
alert('Your JWT is: ' + app.get('token'));
}).catch(function(error){
console.error('Error authenticating!', error);
});
</script>
<main class="login container">
<div class="row">
<div class="col-12 col-6-tablet push-3-tablet text-center">
<h1 class="font-100">Post</h1>
</div>
</div>
<div class="row">
<div class="col-12 col-6-tablet push-3-tablet col-4-desktop push-4-desktop text-center">
<form class="form" method="post" action="/posts">
<fieldset>
<input class="block" type="text" name="title" placeholder="title">
</fieldset>
<fieldset>
<input class="block" type="text" name="description" placeholder="description">
</fieldset>
<button type="submit" class="button button-primary block login">
Post
</button>
</form>
</div>
</div>
</main>
</body>
</html>
Thanks for any help! I really like feathers so far.

Ok so this is what I did and seems to work fine. I wasn't sure if feathers was somehow automagically handling the auth token after it was created. Once I setup the post to send via jquery and setup the authorization header it worked fine. Thanks for all the help. I do like feathers a lot so far!
$(document).ready(function() {
$( ".test-form" ).submit(function( event ) {
var token = app.get('token');
event.preventDefault();
$.ajax({
url: 'http://localhost:3030/posts/',
type: 'post',
data: {
title: $("#title").val(),
description: $("#description").val()
},
headers: {
Authorization: token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
});});

Use the Feathers client. The same app you're using to do authentication.
// Get the Posts service to work with
var postsService = app.service('posts');
// Create a post
postsService.create({
title: $('#title').val(),
description: $('#description').val()
});
// Do something when a Post is created
postsService.on('created', function (post) {
// `post` is the newly created post
// this callback will run whenever a post is created
console.log(post);
});
You could even use the postsService.create method in an event handler, something likeā€¦
$('form').on('submit', function () {
postsService.create({
title: $('#title').val(),
description: $('#description').val()
});
});

Read this section: http://docs.feathersjs.com/authentication/client.html
You can get token with app.get('token').

when you post the data, set the header field in Authorization -> token which you get when you login.

Related

AJAX return from SmartyStreets API

I am having trouble actually returning any kind of object using this AJAX call. I know I am doing something wrong, but I have no idea where. I hope someone can help me I am looking to return an element in the object "zip". I would like to have any response really, but I can not get anything back.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var result = $('#resultDiv')
$.ajax({
url: 'https://us-street.api.smartystreets.com/street-address',
method: 'get',
data: {
auth-id='your-auth-id',
auth-token='your-auth-token',
street=$('#street'),
city=$('#city'),
state=$('#state')
},
dataType: 'json',
success: function(data) {
if (data = null)
{
result.html('You failed');
}
else {
result.html('Match:' + data.components[0].zipcode)
}
}
});
});
});
</script>
<title>SSTest</title>
</head>
<body>
<div class="container">
<h1 style="text-align:center"> Welcome to Address Check </h1>
<form action="#" method="post">
<div class="form-group">
<label for="street">Street</label>
<input type="text" id="street" class="form-control" name="street">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" class="form-control" name="city">
</div>
<div class="form-group">
<label for="state">State</label>
<input type="text" id="state" class="form-control" name="state">
</div>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
<br/>
<br/>
<div id="resultDiv"></div>
</body>
</html>
As you are using a GET call, you can test this in the browser first AND make sure you are getting a response before you start wrapping it in a JQuery call.
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=SOMETHING&state=SOMETHING&city=SOMETHING
If you get a non-result, then consult the API to see if you are passing the correct parameters.
Using the DOCS, this call returns data for your API Keys -
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10
This JQuery Get HTML example gets a response -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10", function(data, status){
alert("zipcode: " + JSON.stringify(data));
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
You should be able to build from that as you refine your JQuery understanding to get exactly what you need.
I was able to find a handful of errors with your code and fixed them here in this JSFiddle. Here are the list of errors you had.
Don't include your auth-id, auth-token in public code. You're giving away your address lookups by doing this. You should go remove these from your account and generate new ones.
In your original success function you didn't do a compare. You should use == here. Actually, the API will never send back null for data on success so you don't even need this here anymore. Use the error function instead.
The data object passed in the ajax call is done incorrectly. You should not be using =, instead use :.
In the data object you should call .val() after the jQuery selectors to get the values entered into those fields.
data.components[0].zipcode should be data[0].components.zipcode. The api will return back a data array of objects. components is not an array.
The auth-id and token should only be used when used from server side.
It is clearly mentioned not to expose the auth-id and auth-token in the documentation.
I used the FETCH API from Javascript and the code looks like this:
var key = '' //your embedded key here
var street = encodeURIComponent('1600 amphitheatre pkwy');
var city = encodeURIComponent('mountain view');
var state = 'CA';
var url = 'https://us-street.api.smartystreets.com/street-address?street=' + street + '&city=' + city + '&state=' + state + '&key=' + key;
const response = await fetch(url)
const responseData = await response.json()

Connecting Node.JS to HTML Form

I am new to node.js and I'm trying to create an easy way for a user to input data into an html form, then on the click of submit the data is passed to a node.js script. The node.js script is a post script that takes the user's inputed data and then makes a post to a API and takes a return in JSON from the API. I am trying to get the returned JSON to be printed back onto the html page. How do you do this in a clean and easy manner?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Commute | Ad-hoc</title>
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container cf">
<div class="container cf">
<div>
<h1>Manual Query</h1>
<label>Mode</label>
<select id="modes">
<option value="driving">Driving</option>
<option value="walking">Walking</option>
<option value="cycling">Cycling</option>
</select>
<label>Latitude Origin</label>
<input type="text" name="latitude_origin" id="latitude_origin" value="37.791871">
<label>Longitude Origin</label>
<input type="text" name="longitude_origin" id="longitude_origin" value = "-122.396742">
<label>Latitude Destination</label>
<input type="text" name="latitude_dest" id="latitude_dest" value = "37.782461">
<label>Longitude Destination</label>
<input type="text" name="longitude_dest" id="longitude_dest" value = "-122.454807">
<button id="singleQuery" class="singleQuery" input type="default small">Run</button>
</div>
<div>
<h1>Multi-Query (.tsv)</h1>
<label>Upload</label>
<input type="file" name="pic" id="laserPrinters">
<button id="testLaser" class="default small" input type="default small">Run</button>
</div>
<div>
<h1>Result</h1>
<textarea rows="4" cols="50"> </textarea>
</body>
</html>
<script type="text/javascript">
var mode = $("#modes").val();
var latitude_origin = $("#latitude_origin").val();
var longitude_origin = $("#longitude_origin").val();
var latitude_dest = $("#latitude_dest").val();
var longitude_dest = $("#longitude_dest").val();
</script>
My Node.JS post script:
var request = require("request");
var options = { method: 'POST',
url: 'http://blah:8000/blah/blah/blah/blah/[latitude_origin]/[longitude_origin]/',
headers:
{ 'postman-token': 'blah',
'cache-control': 'no-cache' },
body: '{"query1":[latitude_dest,longitude_dest]}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
First, you have to setup a server to listen to the requests that you will send to your node.js web api.
I really like recommend you use express.js. It is a very powerful web server.
Read more in:
https://expressjs.com/
I am writing some example for you soon.
Hope it help you.
UPDATE 1
Take a look at MEAN Stack
https://github.com/meanjs/mean
UPDATE 2
Here are some examples:
https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application
https://developers.openshift.com/languages/nodejs/example-meanstack.html

Google drive save to not working (Google drive api)

I am trying to make a website that will save a cat into the account of the user and have tried this:
<script src="https://apis.google.com/js/platform.js"></script>
<div class="g-savetodrive"
data-src="http://example.com/pug-snores.mp3"
data-filename="pug-snores.mp3"
data-sitename="A Snoring Pug">
</div>
The save icon shows up but it does not save to the drive.
Why?
Thanks
try the explicit render: code from the google javascript api
<!DOCTYPE html>
<html>
<head>
<title>Save to Drive Demo: Explicit Render</title>
<link rel="canonical" href="http://www.example.com">
<script src="https://apis.google.com/js/platform.js">
{parsetags: 'explicit'}
</script>
</head>
<body>
Render the Save to Drive button
<div id="savetodrive-div"></div>
<script>
function renderSaveToDrive() {
gapi.savetodrive.render('savetodrive-div', {
src: '//example.com/path/to/myfile.pdf',
filename: 'My Statement.pdf',
sitename: 'My Company Name'
});
}
document.getElementById('render-link').addEventListener('click', renderSaveToDrive);
</script>
</body>
</html>
The data-src URL can be served from another domain but the responses from the HTTP server needs to support HTTP OPTION requests and include the following special HTTP headers:
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Range
Access-Control-Expose-Headers: Cache-Control, Content-Encoding, Content-Range
If you want upload a local file with input file form and/or without php lib would be ...
<!DOCTYPE html>
<html>
<head>
<title>Save to Drive Demo: Explicit Render</title>
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<form id="GDrive" name="GDrive" enctype="multipart/form-data" method = "post">
<input type="file" id="file" name="file" onChange="renderSaveToDrive('savetodrive-div', this.files[0].name,'GDrive');"><div id="savetodrive-div"></div>
</form>
<script>
function renderSaveToDrive(namediv, namefile, idfrm) {
window.___gcfg = {
lang: 'es-ES',
parsetags: 'explicit'
};
var xhr = new XMLHttpRequest();
var fd = new FormData(document.forms.namedItem(idfrm));
fd.append("file_new_name", namefile);
xhr.open("POST", location.href);
xhr.send(fd);
gapi.savetodrive.render(namediv, {
src: namefile,
filename: namefile,
sitename: 'GDrive Demo: Explicit Render'
});
}
</script>
</body>
</html>

Unable to call simple REST web service from ajax

I am developing an web application using rest web services. I am trying to call the simple web service from the ajax. But I am not getting desired output.
My web service code is:
#Path("hello")
public class Hello {
#GET
#Path("/first")
#Produces("text/html")
public String function1(){
return "Something happens";
}
}
and my html file which gives ajax call for rest web service is:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function callme(){
alert("hello");
$.ajax({
type: "GET",
url: "http://localhost:8080/WebApplication4/webresources/hello/first",
data:"",
dataType:"text",
contentType: "text/html",
success: function(resp){alert("Server says" + resp);},
error: function(e){ alert("An error has occured");},
});
}
</script>
</head>
<body>
<form id="form1" method="GET" onsubmit="callme();">
<input type="text" name="t1">
<input type="submit" Value="SUBMIT">
</form>
</body>
</html>
When I call web service from the browser, then my web service gives return value as expected.
I call web service from browser as http://localhost:8080/WebApplication4/webresources/hello/first
and it return with text "Something happens"
What goes wrong here with ajax call?
And also How can capture the returned json object in ajax?
Thank you
This is the correct way to do it.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function callme(){
alert("hello");
$.ajax({
type: "GET",
url: "https://localhost/codeTest.php",
data:"",
dataType:"text",
contentType: "text/html",
success: function(resp){alert("Server says" + resp);},
error: function(e){ alert("An error has occured");},
});
}
</script>
</head>
<body>
<form id="form1" method="GET">
<input type="text" name="t1">
<input type="button" Value="SUBMIT" onclick="callme();">
</form>
</body>
The ajax call has to made from html input type button click event, not on form submit. Form submit event reloads the page and it doesn't wait for ajax response.

binding data web service public url to dropdown in excelcontentApp

Here i have created web service and given public url for getting data from the data.I have written following code in office 365 developer preview(NAPA) default.htm page.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>DemoApplication</title>
<link rel="stylesheet" type="text/css" href="../Content/Office.css" />
<!-- Add your CSS styles to the following file -->
<link rel="stylesheet" type="text/css" href="../Content/App.css" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script src="https://appsforoffice.microsoft.com/lib/1.0/hosted/office.js"></script>
<!-- Add your JavaScript to the following file -->
<script src="../Scripts/App.js"></script>
</head>
<body onload="GetData()">
<select id="CbxArea" style="width: 200px">
<option>Select Area</option>
</select>
<input type="button" value="submit" id="btnsubmit"/>
</div>
</body>
</html>
fallowing code is written in app.js file
Office.initialize = function (reason) {
};
function GetArea(){
var ddlArea = $("#CbxArea");
$.ajax({
type: "POST",
url: "http://192.168.3.252:8081/HaraveerWCF/ExcelDataService.asmx/GetAreaNames",
contentType: "application/json; charset=utf-8",
//url:"ExcelDataService.asmx/GetAreaNames",
dataType: "json",
success: function (data) {
for (i = 0; i < data.d.length; i++) {
ddlArea.append($("<option></option>").val(data.d[i].AreaName).html(data.d[i].AreaName));
}
},
failure: function (msg) {
alert(msg);
}
});
}
Where i have written wrong.Please help me out.Make sure total code is written in only online office 365 portal account.Not written in visual studio.
You have done little bit, we can say override to options html. You are placing values and the text of the each options:
for (i = 0; i < data.d.length; i++) {
ddlArea.append($("<option></option>").val(data.d[i].AreaName)
.text(data.d[i].AreaName));
}
You can achieve this with $.each():
$.each(data.d, function(i, v){
ddlArea.append("<option></option>").val(v[i].AreaName).text(v[i].AreaName);
});
With jQuery 1.4+, you could just do
for (i = 0; i < data.d.length; i++) {
ddlArea.append($('<option/>', { value : data.d[i].AreaName }).text(data.d[i].AreaName);
}
You may have run into a JavaScript cross-domain data access issue as you're trying to access a remote address from you Office 365 Preview site. If the return type of the request to the remote address is JSONP, then you may be able to override the cross-domain data access issue.
Check with your browser Developer Tools (invoke it with F12 keyboard shortcut & then look under Network tab) or Firefox Firebug if the remote server URL returns any JSONP data.