I successfully generated an access token but now I can't use it. Sadly there is no official yandex node library for using the API. There are 2 unofficial npm module that will only work with a server but I want it localhost. As example with code like this, in this case I want to display all files from my disk. Of course I enabled all scopes for my app
request.get('https://cloud-api.yandex.net/v1/disk/resources/files/', {
'auth': {
'bearer': 'xxxxxxxxxxxxxxxxxxx'
}
}, function(err,httpResponse,body){ /* ... */
if(err) {
console.log('err: ' + err)
}
console.log('body: ' + body)
});
Also if I would use https://cloud-api.yandex.net/v1/disk/resources/files?oauth_token=xxxxxxxxxxxxxx&oauth_client_id=xxxxxxxxxxxxxxxxxxx
or https://cloud-api.yandex.net/v1/disk/resources/files?access_token=xxxxxxxxxxxxxx&client_id=xxxxxxxxxxxxxxxxxxx
in my browser I would get
{"message":"?? ???????????.","description":"Unauthorized","error":"UnauthorizedError"}
Somebody has working code or an idea why I´am getting this message?
Now I'm using yandex-disk package. It works enougth for my purposes.
That my steps:
Register app in Yandex Oath Service.
After that I can get info about my app
Realize the access method to get Oath Token by calling this.
npm i yandex-disk
Inserting the code into index.js
const YandexDisk = require('yandex-disk').YandexDisk;
const disk = new YandexDisk('YourOathTokenHere');
console.log('disk', disk);
disk.readdir('/', (err, response) => {
console.log('callback error', err);
console.log('callback response', response);
});
Just include authorization header like that:
axios.get(encodeURI(`https://cloud-api.yandex.net:443/v1/disk/resources?path=${path}`), {
headers: {
'Authorization': `OAuth ${token}`
}
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
Related
I currently have a scheduled function running as a cloud function that uses Axios to write to the Realtime Database in Firebase. However, I continue to receive the error:
'Request failed with status code 401'
Which seems to be an authorization error. I am using Axios with authorization using a legacy token, specifically the secret for the database.
Am I using authorization wrong here or is there another way to do this? The issue I have is using authorization for access specifically in a scheduled function.
App.js
exports.callTo = functions.pubsub.schedule("* * * * *").onRun((context) => {
let searchTrends;
googleTrends.dailyTrends({
trendDate: new Date("2021-10-20"),
geo: "US",
}, function(err, res) {
if (err) {
functions.logger.error(err);
} else {
searchTrends = JSON.parse(res).default.trendingSearchesDays
.trendingSearches;
const query = searchTrends[2] + " since:2021-10-20";
return axios.put("https://testtter-c0e48-default-rtdb.firebaseio.com/searchTrends.json?auth=<account_secret>", {trends: searchTrends})
.then((res) => {
functions.logger.log("Result: " + res);
})
.catch((error) => {
functions.logger.log("Error: " + error);
});
}
});
});
I'm working on a Node-express-react project where I'm calling the Google Analytics reporting API to display some data on the client-side. Right now I have:
my back-end and my front-end on two separate localhosts
A Google Sign-in Button on the front-end redirecting to the back-end to run the OAuth 2.0 authentication process
I'm calling the ga reporting API once I have the token.
Everything is working well so far. Now I'd like to pass the response from the API call to the client-side (react). I have the following component:
componentDidMount() {
// Pick whatever host/port your server is listening on
fetch('http://localhost:5000/getData')
.then(res => { // <-- The `results` response object from your backend
// fetch handles errors a little unusually
if (!res.ok) {
throw res;
}
// Convert serialized response into json
return res.json()
}).then(data => {
// setState triggers re-render
this.setState({loading: false, data});
}).catch(err => {
// Handle any errors
console.error(err);
this.setState({loading: false, error: true});
});
}
Here is my API call on the server-side
router.get('/getData', function(req, res) {
var token = req.query.token;
request('https://www.googleapis.com/analytics/v3/management/accounts?access_token=' + token, function (error, response, body) {
if(error){
console.log(error);
}else{
console.log(JSON.parse(body))
let views = []
JSON.parse(body).items.forEach(view => {
views.push({
name: view.webPropertyId + ' - ' + view.name + ' (' + view.websiteUrl + ')',
id: view.id
})
})
console.log(views)
res.send(views);
}
});
})
The issue is that the componentDidMount() is being called before I click the Google login button which is running into an error because data from the API are not available (since no authentication has been done yet).
Which logic I should follow to have my data being fetch only once the login has been successful?
Thanks.
This morning I deployed a MERN stack login app in heroku successfully. But, when I tried to login
GET http://localhost:5000/user/login/email/password net::ERR_CONNECTION_REFUSED
in the console.
I understood that that the error is because I am making get request in axios using
axios.get("http://localhost:5000/user/login/" + this.state.email + "/" + this.state.password).then((res) => {
if (res.status === 200) {
this.setState({ status: res.status, name: res.data.name });
console.log(res.data);
}
else
throw new Error(res.status);
}).catch((err) => {
this.setState({ isInvalid: true });
})
But, the port is being dynamically allocated on the server side.
const port = process.env.PORT||5000;
app.listen(port, () => {
console.log("Server started on port:" + port);
});
Tried allocating only hardcoded value to the port. Still no luck
There are lots of mistakes in your code. You have deployed your app but your URL is still localhost which is not Heroku URL. First of all you need to setup env variables for your application like this.
You can put this in some constant file from where you get your end point. Don't write END POINTS directly in the ajax calls. Use constant and create a single file for from where you do all the ajax calls of the application.
You can set the env for both frontend and backend and this is how you should work. The development env should be separate from production one.
if (process.env.NODE_ENV === "development") {
API = "http://localhost:8000";
} else if (process.env.NODE_ENV === "production") {
API = "https://be-prepared-app-bk.herokuapp.com";
}
Don't use GET for the login and sending email and password in parameters. You should use POST and send all the data in body.
Here's how you single ajax file should look alike:
import { API_HOST } from "./constants";
import * as auth from "../services/Session";
const GlobalAPISvc = (endPoint, method, data) => {
const token = auth.getItem("token");
const uuid = auth.getItem("uuid");
return new Promise((resolve, reject) => {
fetch(`${API_HOST}${endPoint}`, {
method: method,
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
"x-authentication": token,
uuid: uuid
}
})
.then(res => {
return res.json();
})
.then(json => {
resolve(json);
})
.catch(error => {
reject(error);
});
}).catch(error => {
return error;
});
};
export default GlobalAPISvc;
I have created an application in MERN which I made public on GitHub. Feel free to take help from that. Repository Link
Firstly, I would suggest you, not to use get request method for login.
Secondly, if you've deployed your backend code then use dynamic url provided by heroku for login request.
e.g. if your url is xyz.heroku.com then axios.get('xyz.heroku.com/user/login/'+email+'/'+password);
as now you don't need to hard-code the port or use localhost.
I am calling my get rest service like this,
makeGetCall(url: string): Observable<any> {
const headers = new Headers({'auth-code': 'auth-code',
'from':'app'});
return this.http.get(AdminConstants.BASE_URL + this.SEPARATOR + url,{
headers: headers
})
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
console.log('extract data');
console.log(res);
const body = res.json();
return body || {};
}
private handleErrorObservable(error: Response | any) {
console.log('error in service');
console.log(error.message);
return Observable.throw(error.message || error);
}
and My rest service is:
console.log('inside get all user');
ApiUser.find().then(users => {
console.log('length : '+users.length)
res.status(200).send(users);
}, error => {
res.send(500).send(error);
})
I am using MEAN stack for my application.
Here is my problem, when I am calling my rest service from postman its working.Even in the chrome/mozilla console I can see my response as expected.response header
But from my angular 2 application my handleErrorObservable method is called and that too with an error without proper message.
I just installed ssl certificates on my server, before ssl this was working inside my application.
Also to add post requests are working.
I don't know what I am missing.
Please help.
Thanks in advance.
Thanks to #kirkLarkin
I just added res.set('Access-Control-Allow-Origin','*'); in my rest service and it worked.
I have an App written using the HapiJs framework for Node and want to connect it to a CouchDb databse, but am having trouble finding the code to do so.
Can anyone help me with the code to do that? What is the 'normal' way of doing that?
Cheers!
Well you don't need any framework for couchdb. Everything is available via a rest api. Just use request module to make requests to the api. A few examples : -
Read a document
request.get("http://localhost:5984/name_of_db/id_of_docuement",
function(err,res,data){
if(err) console.log(err);
console.log(data);
});
Read from a view
request.get(
"http://localhost:5984/name_of_db/_design/d_name/_view/_view_name",
function(err,res,data){
if(err) console.log(err);
console.log(data);
});
The entire api is documented here
There is no need to manage connections or to handle the opening and closing of database that you might be doing with other databases. Simply start couchdb and start making requests to from your application.
However if you find that making requests to the api directly is a bit cumbersome for you, then you can try using nano which provides a nicer syntax for doing things with couchdb.
Some snippets of code
All right so I am not familliar with hapi so I will just tell you how do do it with request.
Consider this example from the docs
var Hapi = require('hapi');
var server = new Hapi.Server(3000);
var request = require("request");
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: function (req, rep) {
request.get("http://localhost:5984/name_of_db/id_of_docuement",
function(err,res,data){
if(err) console.log(err);
rep(data);
});
}
});
server.start(function () {
console.log('Server running at:', server.info.uri);
});
When you call the / endpoint it the request handler for it is executed. It makes a request to a couchdb endpoint to fetch a a document. You don't need anything to connect to couchdb besides that.
Another option could be the hapi-couchdb plugin (https://github.com/harrybarnard/hapi-couchdb).
Using it is a little more "hapi-like" than making direct calls into the Couch API directly.
Here's an example from the plugin documentation:
var Hapi = require('hapi'),
server = new Hapi.Server();
server.connection({
host: '0.0.0.0',
port: 8080
});
// Register plugin with some options
server.register({
plugin: require('hapi-couchdb'),
options: {
url: 'http://username:password#localhost:5984',
db: 'mycouchdb'
}
}, function (err) {
if(err) {
console.log('Error registering hapi-couchdb', err);
} else {
console.log('hapi-couchdb registered');
}
});
// Example of accessing CouchDb within a route handler
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
var CouchDb = request.server.plugins['hapi-couchdb'];
// Get a document from the db
CouchDb.Db.get('rabbit', { revs_info: true }, function(err, body) {
if (err) {
throw new Error(CouchDb.Error(error); // Using error decoration convenience method
} else {
reply(body);
});
}
});
server.start(function() {
console.log('Server running on host: ' + server.info.uri);
});