calling variable outside the function - javascript

I'm trying to develop a web page that get the data from another web application using axios.get and I wanna insert this data into the Postgres database, the problem is data is inside the then promise, I can not access it to insert it to the database, how can I do that or how can I access the data outside the then
I wanna insert var rn0 ty0
this is the main.js
const axios = require('axios')
const InsertToDataBase = require("./InsertToDataBase");
const username = 'admin'
const password = 'admin'
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const urlLAMP_0 = 'http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la'
const urlLAMP_1 = 'http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la'
function getDataLAMP_0(){
axios.get(urlLAMP_0, {
headers: {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin':'*',
"X-M2M-RI":"OM2M-webpage",
'Authorization': `Basic ${token}`,
'Accept': 'application/json',
'mode': 'cors',
'credentials': 'include',
}
})
.then(function(response) {
document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
var rn0 = response.data['m2m:cin'].rn;
document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
var ty0 = response.data['m2m:cin'].ty;
document.getElementById("ri0").textContent = response.data['m2m:cin'].ri;
document.getElementById("pi0").textContent = response.data['m2m:cin'].pi;
document.getElementById("ct0").textContent = response.data['m2m:cin'].ct;
document.getElementById("lt0").textContent = response.data['m2m:cin'].lt;
document.getElementById("st0").textContent = response.data['m2m:cin'].st;
document.getElementById("cnf0").textContent = response.data['m2m:cin'].cnf;
document.getElementById("cs0").textContent = response.data['m2m:cin'].cs;
document.getElementById("con0").textContent = response.data['m2m:cin'].con;
})
}
getDataLAMP_0();
InsertToDataBase.insertdatatolamp0(rn0,ty0);
this is the InsertToDataBase.js
const {Client} = require('pg')
const client = new Client({
user:"postgres",
password:"admin",
host:"localhost",
port:"5432",
database:"postgres",
})
function insertdatatolamp0(rn0,ty0){
client.connect()
.then(()=>console.log("connected successfuly"))
.then(()=>client.query("insert into lamp0 values ($1,$2)",[rn0,ty0]))
.catch(e=> console.log(e))
.finally(()=> client.end())
}
module.exports = { insertdatatolamp0 };

You can chain promises. This will give you enough flexibility to do a series of actions one after the other, in your case change textContent and then insert some values into the database.
const axios = require("axios");
const InsertToDataBase = require("./InsertToDataBase");
const username = "admin";
const password = "admin";
const token = Buffer.from(`${username}:${password}`, "utf8").toString("base64");
const urlLAMP_0 = "http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la";
const urlLAMP_1 = "http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la";
function getDataLAMP_0() {
axios
.get(urlLAMP_0, {
headers: {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "*",
"X-M2M-RI": "OM2M-webpage",
Authorization: `Basic ${token}`,
Accept: "application/json",
mode: "cors",
credentials: "include",
},
})
.then(function (response) {
document.getElementById("rn0").textContent = response.data["m2m:cin"].rn;
document.getElementById("ty0").textContent = response.data["m2m:cin"].ty;
document.getElementById("ri0").textContent = response.data["m2m:cin"].ri;
document.getElementById("pi0").textContent = response.data["m2m:cin"].pi;
document.getElementById("ct0").textContent = response.data["m2m:cin"].ct;
document.getElementById("lt0").textContent = response.data["m2m:cin"].lt;
document.getElementById("st0").textContent = response.data["m2m:cin"].st;
document.getElementById("cnf0").textContent =
response.data["m2m:cin"].cnf;
document.getElementById("cs0").textContent = response.data["m2m:cin"].cs;
document.getElementById("con0").textContent =
response.data["m2m:cin"].con;
return response;
})
.then((response) => {
var rn0 = response.data["m2m:cin"].rn;
var ty0 = response.data["m2m:cin"].ty;
InsertToDataBase.insertdatatolamp0(rn0,ty0);
});
}
getDataLAMP_0();

You can do this with the help of Promise, here is a simple example
async function httpGetDataHandler() {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
const parsedJson = await response.json();
const data = await parsedJson;
return Promise.resolve(data);
}
const getDataLAMP_0 = () => {
httpGetDataHandler()
.then((data) => {
// do your document.getElementById stuff in here
// I'm just returning the first index value, you can do whatever you want like return rn0
return data[0]
})
.then((data) => {
console.log("insert to database: ", data);
});
};
getDataLAMP_0();

Related

Authenticatin for HERE RouteMatching API

I'm trying to use HERE's RouteMatching API of JavaScript
Current full code is here: https://github.com/code4history/ShibeContour/blob/d7e56a7/here_mapmatcher.js
For authentication, I coded like this:
import properties from "properties"
import hmacSHA256 from 'crypto-js/hmac-sha256.js'
import Base64 from 'crypto-js/enc-base64.js'
import fetch from 'node-fetch'
import {promises as fs} from "node:fs"
const getProps = async () => {
return new Promise((res) => {
properties.parse("./credentials.properties", {path: true}, function (error, data) {
res(data)
})
})
}
const getToken = async (props) => {
const nonce = `${performance.now()}`
const timestamp = Math.floor((new Date()).getTime() / 1000)
const parameters = [
"grant_type=client_credentials",
`oauth_consumer_key=${props["here.access.key.id"]}`,
`oauth_nonce=${nonce}`,
"oauth_signature_method=HMAC-SHA256",
`oauth_timestamp=${timestamp}`,
"oauth_version=1.0"
].join("&")
const encoding_params = encodeURIComponent(parameters)
const base_string = `POST&${encodeURIComponent(props["here.token.endpoint.url"])}&${encoding_params}`
console.log(base_string)
const signing_key = `${props["here.access.key.secret"]}&`
const hmac_digest = encodeURIComponent(Base64.stringify(hmacSHA256(base_string, signing_key)))
const headers = {
"Authorization": `OAuth oauth_consumer_key="${props["here.access.key.id"]}",oauth_nonce="${nonce}",oauth_signature="${hmac_digest}",oauth_signature_method="HMAC-SHA256",oauth_timestamp="${timestamp}",oauth_version="1.0"`,
"Cache-Control": "no-cache",
"Content-Type": "application/x-www-form-urlencoded"
}
const body = `grant_type=client_credentials`
const response = await fetch(props["here.token.endpoint.url"], {
method: 'post',
body,
headers
})
return response.json()
}
This works well, I got authentication token successfully.
Like this:
{
access_token: 'eyJhbGciOiJSUzUxMiIsImN0eSI6IkpXVCIsImlzcyI6IkhFUkUiLCJhaWQiOiJIZ0NSaFV4...',
token_type: 'bearer',
expires_in: 86399,
scope: 'hrn:here:authorization::org...'
}
But even I used this access_token, route matching call causes authentication error.
Code is:
const main = async () => {
const props = await getProps()
const token_data = await getToken(props)
const body = await fs.readFile("gps/8DD83AC3-8B5A-4108-9CC0-2B78CF9936EC.kml", {encoding: "UTF-8"})
const headers = {
"Authorization": `Bearer ${token_data.access_token}`,
"Cache-Control": "no-cache",
"Content-Type": "application/octet-stream"
}
const response = await fetch(`https://routematching.hereapi.com/v8/calculateroute.json?routeMatch=1&mode=fastest;car;traffic:disabled&apiKey=${props["here.access.key.id"]}`, {
method: 'post',
body,
headers
})
const respond = await response.json()
console.log(respond)
}
main()
Error response was like this:
{
error: 'Forbidden',
error_description: 'These credentials do not authorize access'
}
What is wrong?
I can't imagine what is wrong.
Finally I found the reason
API URL is not match.
We can find many candidate urls,
https://fleet.api.here.com/2/calculateroute.json
https://routematching.hereapi.com/v8/calculateroute.json
etc...
but true working url is only
https://routematching.hereapi.com/v8/match/routelinks
which we can find in this document.
https://platform.here.com/services/details/hrn:here:service::olp-here:route-matching-8/api-ref
Once I changed API endpoint to this correct one, it works well.

Unable to invoke "btoa" and "item.slice" method in my script for retrieving the playlist

Whenever I am trying to invoke the "btoa" method, I am not able to use this within my script. I created a variable to store the client id: client_secret in base64. The id and secrets are being retrieved from the ".env" file.
I have also tried to use the Buffer method, but unable to use this as well. I am getting the error "invalid from" in Buffer.
can someone help me?
Please look at the full code,
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN;
const basic = btoa(`${client_id}:${client_secret}`);
const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`;
const TOP_TRACKS_ENDPOINT = `https://api.spotify.com/v1/me/top/tracks`;
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
const getAccessToken = async () => {
const response = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token
})
});
return response.json();
};
export const getNowPlaying = async () => {
const { access_token } = await getAccessToken();
return fetch(NOW_PLAYING_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`
}
});
};
export const getTopTracks = async () => {
const { access_token } = await getAccessToken();
return fetch(TOP_TRACKS_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`
}
});
};
Using the above script I am trying to embed the customized Spotify play on my site. This wrapper is intended to display the top track as well.
Also, whenever I am trying to run the wrapper used to display the top tracks, it displays the following error,
Full code for displaying the top tracks:
import { type NextRequest } from 'next/server';
import { getTopTracks } from 'lib/spotify';
export const config = {
runtime: 'experimental-edge'
};
export default async function handler(req: NextRequest) {
const response = await getTopTracks();
const { items } = await response.json();
const tracks = items.slice(0, 10).map((track) => ({
artist: track.artists.map((_artist) => _artist.name).join(', '),
songUrl: track.external_urls.spotify,
title: track.name
}));
return new Response(JSON.stringify({ tracks }), {
status: 200,
headers: {
'content-type': 'application/json',
'cache-control': 'public, s-maxage=86400, stale-while-revalidate=43200'
}
});
}
The problem is that you misspelled the Bytes to ASCII function, it is btoa, not btao.
If you are looking to do it the other way around, spell it atob.

Uncaught TypeError: net.Socket is not a constructor

I use browserify to let me use require() in my javascript code but it generates code that contains net.Socket() which give Uncaught TypeError: net.Socket is not a constructor. in the browser
is there any solution for that?
node version v14.17.4
browserify 17.0.0
this is my main code
tryjson.js
const axios = require('axios');
const InsertToDataBase = require("./InsertToDataBase");
const username = 'admin'
const password = 'admin'
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const urlLAMP_0 = 'http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la'
const urlLAMP_1 = 'http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la'
function getDataLAMP_0(){
axios.get(urlLAMP_0, {
headers: {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin':'*',
"X-M2M-RI":"OM2M-webpage",
'Authorization': `Basic ${token}`,
'Accept': 'application/json',
'mode': 'cors',
'credentials': 'include',
}
})
.then(function(response) {
document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
document.getElementById("ri0").textContent = response.data['m2m:cin'].ri;
document.getElementById("pi0").textContent = response.data['m2m:cin'].pi;
document.getElementById("ct0").textContent = response.data['m2m:cin'].ct;
document.getElementById("lt0").textContent = response.data['m2m:cin'].lt;
document.getElementById("st0").textContent = response.data['m2m:cin'].st;
document.getElementById("cnf0").textContent = response.data['m2m:cin'].cnf;
document.getElementById("cs0").textContent = response.data['m2m:cin'].cs;
document.getElementById("con0").textContent = response.data['m2m:cin'].con;
return response;
})
.then((response) => {
var rn0 = response.data["m2m:cin"].rn;
var ty0 = response.data["m2m:cin"].ty;
InsertToDataBase.insertdatatolamp0(0,1);
})
}
function getDataLAMP_1(){
axios.get(urlLAMP_1, {
headers: {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin':'*',
"X-M2M-RI":"OM2M-webpage",
'Authorization': `Basic ${token}`,
'Accept': 'application/json',
'mode': 'cors',
'credentials': 'include',
}
})
.then(function(response) {
document.getElementById("rn1").textContent = response.data['m2m:cin'].rn;
document.getElementById("ty1").textContent = response.data['m2m:cin'].ty;
document.getElementById("ri1").textContent = response.data['m2m:cin'].ri;
document.getElementById("pi1").textContent = response.data['m2m:cin'].pi;
document.getElementById("ct1").textContent = response.data['m2m:cin'].ct;
document.getElementById("lt1").textContent = response.data['m2m:cin'].lt;
document.getElementById("st1").textContent = response.data['m2m:cin'].st;
document.getElementById("cnf1").textContent = response.data['m2m:cin'].cnf;
document.getElementById("cs1").textContent = response.data['m2m:cin'].cs;
document.getElementById("con1").textContent = response.data['m2m:cin'].con;
})
}
getDataLAMP_0();
getDataLAMP_1();
setInterval(getDataLAMP_0,100);
setInterval(getDataLAMP_1,100);
InsertToDataBase.js
const {Client} = require('pg')
const client = new Client({
user:"postgres",
password:"admin",
host:"localhost",
port:"5432",
database:"postgres",
})
function insertdatatolamp0(rn0,ty0){
client.connect()
.then(()=>console.log("connected successfuly"))
.then(()=>client.query("insert into lamp0 values ($1,$2)",[rn0,ty0]))
.catch(e=> console.log(e))
.finally(()=> client.end())
}
module.exports = { insertdatatolamp0 };
if i understood correctly, you have two endpoints serving json data and then you will feed a postgres database with it.
however, the InsertToDataBase.js tries to use the postgre sql driver on browser, therefore the error you are seeing.
that code will run fine on node, but not on browser.
since tryjson.js seems to feed a html document while consumes the json endpoints, you either give up the database part or create a small node server to handle those inserts for you.

How do I return an item from an async funtion

Ive been looking into trying to get information from websites using fetch. Trying async/await was my first solution, and so far it has been going well. Getting the information I needed was a breeze, but trying to retrieve that data in main is my problem. Const data in my main function even with the await tag only returns an undefined object. How can I get the data that I have in the function into my main
import React from "react";
import {
WASTEMANAGEMENT_USERNAME,
WASTEMANAGEMENT_PASSWORD,
WASTEMANAGEMENT_APIKEY_AUTH,
WASTEMANAGEMENT_APIKEY_CUSTID,
WASTEMANAGEMENT_APIKEY_DATA,
} from "#env";
async function login() {
let response = await fetch("https://rest-api.wm.com/user/authenticate", {
method: "POST",
headers: {
"content-type": "application/json",
apikey: WASTEMANAGEMENT_APIKEY_AUTH,
},
body: JSON.stringify({
username: WASTEMANAGEMENT_USERNAME,
password: WASTEMANAGEMENT_PASSWORD,
locale: "en_US",
}),
});
let res = await response.json();
const id = res.data.id;
const access_token = res.data.access_token;
response = await fetch(
`https://rest-api.wm.com/authorize/user/${id}/accounts?lang=en_US`,
{
method: "GET",
headers: {
oktatoken: access_token,
apikey: WASTEMANAGEMENT_APIKEY_CUSTID,
},
}
);
res = await response.json();
const custId = res.data.linkedAccounts[0].custAccountId;
response = await fetch(
`https://rest-api.wm.com/account/${custId}/invoice?userId=${id}`,
{
method: "GET",
headers: {
apikey: WASTEMANAGEMENT_APIKEY_DATA,
token: access_token,
},
}
);
res = await response.json();
res.body.balances.filter((item) => {
if (item.type === "Current") {
console.log(item);
return item;
}
});
}
const WasteManagementLogin = async () => {
const data = await login();
console.log(data);
};
export default WasteManagementLogin;

res.json is not a function - nodejs

I've got this error using res.json to get the return of my function and this is code is been used em anothers places as wrote below, running fine.
async function getPlaylist(req, res, playlistId) {
try {
// const calltoken = await getToken()
// const token = calltoken.data.access_token
// console.log(token)
const config = {
headers: {
'Authorization': 'Bearer ' + 'BQA0K9bKgBVn8xTp-yTsoaKs5VfS7EyjMIL03OEOy05wq08ZmLkNfqbbnsL_hFT1AV2FGN5tAQdeDV1X224', //token,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
const url = 'https://api.spotify.com/v1/playlists/1j2L3DjzZ3SdN64r83Sblj?si=cuvOrPONSO6caE9XD6smEg'
await axios.get(url, config)
.then(function (response) {
var playlist = response
var items = playlist.data.tracks.items
// console.log(items)
const playlistfull = []
items.forEach(index => {
var playlistdata = {
name: index.track.name,
artists: index.track.album.artists[0].name,
album: index.track.album.name,
url: index.track.external_urls.spotify
}
playlistfull.push(playlistdata)
})
return res.json(playlistfull)
})
} catch (error) {
return console.log(error)
}
}
You have to use in NodeJS
Node's res give parameter to function
const router = express.Router();
router
.route('/')
.get((req, res) => {
const playlistId = 'asdf';
getPlaylist(req, res, playlistId);
return;
});

Categories

Resources