I'm trying to run my js script on my apache2 webserver, but when I visit the scripts page or try to use it, it gives me the error "Cannot GET //". My code is below.
const Express = require("express");
const App = Express().use(Express.static(__dirname + '/nodejs'));
const Keys = ["123", "simplewhitelist"];
const secretKey2 = "E);{Q6_<bkrEo;ITBzLfLxTdpMuzSzVIs?}5vyus3l#>+?=>O}uL-(A}M/PJ`w";
const Crypto = require("crypto");
function hmac(secret, data){
const hash = Crypto.createHash("sha512");
hash.update(secret + data + secret);
return hash.digest("hex").toString();
};
App.get("xxxx.xyz:8000/nodejs/checkWhitelist", (request, response) => {
const Key = request.query.Key;
const Gamer = request.query.gamer;
if(Key && Gamer){
const isKeyValid = Keys.find((key) => key !== null && Key == key);
if(isKeyValid){
response.send(hmac(secretKey2, Key + Gamer)) valid
}
else{
response.send("Not Whitelisted");
}
}
else{
response.send("Not Whitelisted");
}
});
App.listen(8000, () => {
console.log("App started");
});
Related
i need to cache a query with redis and node js , the database is aws s3 ,the problem here as a noob ,i will recive the query as a string, i need to encode the keys in the body request so when i will later try to fetsch the data i will use one of those keys(they need to be seperated with '/') can anyone help me with that and bunch of thanks.
here is what i' tried to do:
const { default: axios } = require('axios');
const express = require('express');
const redisClient = require('./helper/Client')
const app = express();
const port = process.env.PORT || 3000
app.use(express.json());
async function fetchApi(species){
const apiResponse = await axios.get(`https://www.fishwatch.gov/api/species/${species}`)
console.log('request sent successfully');
return apiResponse.data
}
async function getSpeciesData(req, res) {
const species = req.body;
const keys = Object.keys(species);
const encodedParams = {};
for (const key of keys) {
const encodedKey = Buffer.from(key).toString('base64');
encodedParams[encodedKey] = species[key];
}
const key = JSON.stringify(encodedParams);
let resultat;
let isCached = false;
const cachedResponse = await redisClient.get(key);
if (cachedResponse) {
isCached = true;
const decodedResponse = Buffer.from(cachedResponse, 'base64').toString('utf-8');
resultat = JSON.parse(decodedResponse);
res.send({
fromCache: isCached,
data: resultat
});
console.log(cachedResponse);
} else {
const responseData = await fetchApi(keys.join('/'));
const encodedResponseData = Buffer.from(JSON.stringify(responseData)).toString('base64');
redisClient.SETEX(key, 3600, encodedResponseData);
res.send(responseData);
}
}
app.post("/fish", getSpeciesData);
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
I was learn create wather app by using node.js form youtube and i just copy the code that he was writing but there code is work properly and my code dose not work
in my code I don't understand this line and after type this line my code is give arror before this every thing is right
const rtd = adata.map((val) => replaceVal(index, val)).join(" ");
res.write(rtd);
the code in this image is written by me and this code is note work
const fs = require('fs');
const http = require('http');
var requests = require('requests');
const replaceVal = (tempval, orgVal) => {
let temperature = tempval.replace('{% tempval %}', orgVal.current.temp_c);
temperature = temperature.replace('{% location %}', orgVal.location.region);
temperature = temperature.replace('{% country %}', orgVal.location.country);
return temperature;
}
const index = fs.readFileSync('index.html', 'utf-8');
const server = http.createServer((req, res) => {
if (req.url == '/') {
requests('https://api.weatherapi.com/v1/current.json?key=fbffa2e936464bd292b70117221308&q=india&aqi=no')
.on('data', (chunk) => {
const jdata = JSON.parse(chunk);
const adata = [jdata];
// console.log(adata)
// console.log(adata[0].current.temp_c)
const rtd = adata.map((val) => replaceVal(index, val)).join(" ");
res.write(rtd);
})
.on('end', function (err) {
if (err) return console.log('connection closed due to errors', err);
res.end();
// console.log('')
});
}
})
server.listen(8000, "127.0.0.1");
this is screen shot of the video
I am having issues trying to connect to a managed database on Digital Ocean which has sslmode=require.
The connection string I have been given to use is as follows:
postgresql://username:password#server:port/mydb?sslmode=require
my db.js file looks like this:
"use strict";
const fs = require('fs')
const pgPromise = require("pg-promise");
const {ConnectionString} = require('connection-string');
const path = require('path');
var options = {
// Initialization Options
};
let pgp = pgPromise(options);
const dotenv = require('dotenv');
dotenv.config();
const a = new ConnectionString('postgresql://username:password#server:port/mydb?sslmode=require')
var cert= fs.readFileSync(__dirname + '/certs/ca-certificate.crt', 'utf8')
a.setDefaults({
params: {
sslrootcert : cert
}
});
var connstring = a.toString();
let dbpool = pgp(connstring);
module.exports = { dbpool };
When I initially start the process, everything seems to go fine, but when I attempt to hit the database I get:
Error: ENOENT: no such file or directory, open 'C:\Users\Me\Documents\GitHub\tester\-----BEGIN CERTIFICATE----- certificate info -----END CERTIFICATE-----
if I change the pgp connection to accept the ConnectionString object instead
eg.
let dbpool = pgp(a); then I seem to connect with the server, but get authentication errors. Changing my connection string to point at my local db with let dbpool = pgp(a)results in me getting strange errors such as column does not exist. But pointing at local with let dbpool = pgp(connstring); seems to work fine. Due to this, I am presuming that I need to be using let dbpool = pgp(connstring);.
The rest of my relevant code (this is just a simple test project for connecting to the managed db) is as follows:
routes/index.js
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
const userrepository_1 = require("../repositories/userrepository");
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* HIT DATABASE. */
router.get('/testdb', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
let userRepos = new userrepository_1.UserRepository();
let userid = yield userRepos.getuserbyusername("myusername");
if (userid == null) {
return res.status(404).send({ auth: false, message: 'No user found' });
}
res.render('dbtest', { userid: userid });
}))
module.exports = router;
repositories/userrepository.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dbProvider = require("../db");
class UserRepository {
constructor() {
this.db = dbProvider.dbpool;
}
getuserbyusername(username) {
return new Promise((resolve, reject) => { resolve(this.db.oneOrNone('SELECT * FROM users
where isdeleted=false AND username=$1', [username])); })
.then((user) => {
if (user != null) {
let uid = user.userid;
return uid;
}
else {
return null;
}
});
}
}
exports.UserRepository = UserRepository;
My directory structure is:
/bin
www
/certs
ca-certificate.crt
/node_modules
/public
/repositories
userrepository.js
/routes
index.js
/views
app.js
db.js
Like I say I think the issue is with let dbpool = pgp(connstring);
Okay, was a simple fix for this. Rather than reading the file with const cert = fs.readFileSync(__dirname + '/certs/ca-certificate.crt', 'utf8'), I just needed to specify the location. Hence:
const path = require('path');
const cs = new ConnectionString('postgresql://username:password#server:port/mydb?sslmode=require');
const sslrootcert = path.join(__dirname, 'ca-certificate.crt');
cs.setDefaults({
params: { sslrootcert }
});
const db = pgp(cs.toString());
(I also moved the certificate to my home directory)
I've created an app in the Partners panel, and I followed this documentation (using Nodejs and Express).
I can get the JSON format for the products' object without any problem. However, when I add to the scopes variable "read_price_rules" I get this error message: "express-example-app refused to connect."
Is this issue caused by the app's permissions?
My app can: Read products, variants, and collections.
Here is the index.js file:
const dotenv = require('dotenv').config();
const express = require('express');
const app = express();
const crypto = require('crypto');
const cookie = require('cookie');
const nonce = require('nonce')();
const querystring = require('querystring');
const request = require('request-promise');
const apiKey = process.env.SHOPIFY_API_KEY;
const apiSecret = process.env.SHOPIFY_API_SECRET;
const scopes = 'read_products,read_price_rules';
const forwardingAddress = "https://53b16008.ngrok.io";
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
app.get('/shopify', (req, res) => {
const shop = req.query.shop;
if (shop) {
const state = nonce();
const redirectUri = forwardingAddress + '/shopify/callback';
const installUrl = 'https://' + shop + '/admin/oauth/authorize?client_id=' + apiKey + '&scope=' + scopes + '&state=' + state + '&redirect_uri=' + redirectUri;
res.cookie('state', state);
res.redirect(installUrl);
}
else { return res.status(400).send('Missing shop parameter. Please add ?shop=your-development-shop.myshopify.com to your request'); }
});
app.get('/shopify/callback', (req, res) => {
const { shop, hmac, code, state } = req.query;
const stateCookie = cookie.parse(req.headers.cookie).state;
if (state !== stateCookie) { return res.status(403).send('Request origin cannot be verified'); }
if (shop && hmac && code) {
// DONE: Validate request is from Shopify
const map = Object.assign({}, req.query);
delete map['signature'];
delete map['hmac'];
const message = querystring.stringify(map);
const providedHmac = Buffer.from(hmac, 'utf-8');
const generatedHash = Buffer.from(crypto.createHmac('sha256', apiSecret).update(message).digest('hex'), 'utf-8');
let hashEquals = false;
try { hashEquals = crypto.timingSafeEqual(generatedHash, providedHmac) }
catch (e) { hashEquals = false; };
if (!hashEquals) { return res.status(400).send('HMAC validation failed'); }
// DONE: Exchange temporary code for a permanent access token
const accessTokenRequestUrl = 'https://' + shop + '/admin/oauth/access_token';
const accessTokenPayload = {
client_id: apiKey,
client_secret: apiSecret,
code,
};
request.post(accessTokenRequestUrl, { json: accessTokenPayload })
.then((accessTokenResponse) => {
const accessToken = accessTokenResponse.access_token;
// DONE: Use access token to make API call to 'shop' endpoint
const shopRequestUrl = 'https://' + shop + '/admin/api/2019-04/discount_codes/lookup.json?code=20OFF';
const shopRequestHeaders = { 'X-Shopify-Access-Token': accessToken, };
request.get(shopRequestUrl, { headers: shopRequestHeaders })
.then((shopResponse) => {
res.status(200).end(shopResponse);
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
} else {
res.status(400).send('Required parameters missing');
}
});
I Just had to reinstall the app after adding an extra scope in the index.js file.
I was using the code provided by the yelp github repository.
const yelp = require('yelp-fusion');
// Place holders for Yelp Fusion's OAuth 2.0 credentials. Grab them
// from https://www.yelp.com/developers/v3/manage_app
const clientId = process.env.clientId;
const clientSecret = process.env.clientSecret;
const searchRequest = {
term:'Four Barrel Coffee',
location: 'san francisco, ca'
};
yelp.accessToken(clientId, clientSecret).then(response => {
const client = yelp.client(response.jsonBody.access_token);
client.search(searchRequest).then(response => {
const firstResult = response.jsonBody.businesses[0];
const prettyJson = JSON.stringify(firstResult, null, 4);
console.log(prettyJson);
});
}).catch(e => {
console.log(e);
});
integrated this code correctly to my server.js and then I got the error
TypeError: yelp.accessToken is not a function
when trying to execute the code from
app.get('/search', function(req, res) {
yelp.accessToken(clientId, clientSecret).then(response => {
var client = yelp.client(response.jsonBody.access_token);
client.search(searchRequest).then(response => {
var firstResult = response.jsonBody.businesses[0];
var prettyJson = JSON.stringify(firstResult, null, 4);
console.log(prettyJson);
});
}).catch(e => {
console.log(e);
});
and I don't know why. It should work correctly.