How do I send a map as a response to an HTTP request? Currently I am sending an array of strings as part of the request. I want to send a nested map along with a bool as a response to a post request. The bool sends find but the map always comes back as empty. I did a bit of research to use the Object.entries method but no dice. Heres the client code:
const { response, request } = require('express');
const express = require('express');
const readline = require('readline/promises');
const app = express();
const port = 3000;
const axios = require('axios');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
if (parsedInput > 0 && parsedInput <= 8) {
let listOfNames = [];
for (let i=0; i<parsedInput; i++) {
let name = await rl.question(`Enter name #${i}\n`);
listOfNames.push(name);
console.log(`Added ${name} to list of players\n`);
}
const serverResponse = axios.post('http://localhost:3000/start', {
params: { names: listOfNames },
}).then(function (response) {
const recievedMap = new Map(Object.entries(response.data.scoreboard));
console.log(recievedMap);
})
.catch(function (error) {
console.log(error);
});
}
Server code:
const express = require('express');
var bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.json());
const port = 3000
var listOfNames = [];
const scoreboard = new Map();
app.post('/start', async (req, res) => {
listOfNames = req.body.params.names;
for(let i = 0; i < listOfNames.length; i++){
scoreboard.set(listOfNames[i],[]);
}
var responseObj = {
gameRunning: true,
scoreboard: JSON.stringify(scoreboard),
};
res.status(200).send(responseObj);
});
app.get('/', function(req, res, next) {
res.send("Welcome to the homepage of bowling");
})
app.listen(port, () => {
console.log('Listening to request on port 3000');
});
Output:
Choose a number:
1)Start a bowling game
2)Exit simulation
1
Ok how many players will there be (MAX: 8 players)
1
Enter name #0
dadada
Added dadada to list of players
{}
EDIT: Axios was sending data fine, however Im having issues accessing it when in my web server. Since I cant access any object, I return nothing. Am I refering to my request.body incorrectly?
Related
I'm attempting to access products in my private Shopify app using the shopify-api-node module but I'm getting a 403 error.
Here's the code I've written with the help of another Stackoverflow post:
const express = require('express');
const path = require('path');
const Shopify = require('shopify-api-node');
const https = require('https');
const fetch = require('node-fetch');
const {request, gql, GraphQLClient} = require('graphql-request');
const app = express();
const port = 3000;
const apikey = "*";
const apipassword = "*";
const endpoint = "https://<store>.myshopify.com/admin/api/2021-07/graphql.json"
const shopify = new Shopify({
shopName: '<store>.myshopify.com',
apiKey: '*',
password: '*',
autoLimit: true
});
app.set('view-engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.render(path.join(__dirname, '/views/index.ejs'));
shopify.product.count()
.then(async (count) => {
if (count > 0) {
const pages = Math.ceil(count / 250);
let products = [];
for (i = 0; i < pages; i++) {
// use Promise.all instead of waiting for each response
const result = await shopify.product.list({
limit: 250,
page: i + 1,
fields: 'id, variants'
});
products = products.concat(result);
}
// products array should have all the products. Includes id and variants
console.log(products);
}
})
.catch(err => {
console.log(err);
});
})
app.get('/treasures', function(req, res) {
res.render(path.join(__dirname, '/views/treasure.ejs'));
});
app.get('/poetry_books', (req, res) => {
res.send('Hello World');
});
app.listen(port);
If anyone could tell me what I'm doing wrong or suggest a better approach that would be amazing.
I don't think you can use the page parameter anymore. Try something like that instead:
let last_id = 0;
do {
const results = await ShopifyAPI.product.list({
limit: 250,
since_id: last_id,
});
// Do something with your product data
last_id = (results.length === 250 ? results[results.length - 1].id : 0);
} while (last_id);
I was trying to display a string on the client-side by fetching the result from serverside but for some reason, it is not displaying the fetched data. When I console log the variable straight on the js file the server successfully prints the string. The program is not exporting the variable to the client-side to display it. I can't figure out where I went wrong. Any help is appreciated. Thanks in advance.
const router = require("express").Router();
const {
callName
} = require("pathJs");
router.route("PathRoute").get(async(req, res) => {
const Result = await callName();
return res.json(Result);
});
module.exports = router;
function name() {
const liner = "this works"
console.log(liner)
//updated
return liner;
}
async function callName() {
const data1 = await name()
return data1;
}
callName()
<p id="insertHere" style="color: white;"></p>
<script>
async function caller() {
await fetch(`http://localhost:5000/api/PATH`)
.then((res) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(res.json())
}, 1000)
})
}).then((response) => {
console.log(response)
document.getElementById("insertHere").innerHTML = response.liner
}
)
}
</script>
const express = require("express");
const cors = require("cors");
const routePath = require("./routePath");
const {
response
} = require("express");
require("dotenv").config({
debug: process.env.DEBUG
});
const port = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
app.use("/api", routePath);
app.listen(port, () => {
console.log(`server is running on port: http://localhost:${port}`);
});
There is no export in pathJs and you want name() to return an object containing liner. You need
function name() {
const liner = "this works"
console.log(liner)
//updated
return {liner};
}
async function callName() {
const data1 = await name()
return data1;
}
callName()
module.exports = { callName };
The backend is probably crashing with TypeError: callName is not a function while handling the request and therefore doesn't send a response.
I have a written a crawler in Axios and trying to send file via Express, I have around 10 crawlers and 10 html forms methods in Express.
But when I press button it downloads blank file and then crawlers start to run.
It should download file when crawler is finished and save data. but how to do that?
Crawler code:
"use strict"
const axios = require("axios").default;
const cheerio = require("cheerio");
const fs = require("fs");
var excel = require('excel4node');
let writeStream = fs.createWriteStream('mpRera_Agents.csv');
writeStream.write(`AgentName,AgentPhone,AgentEmail\n`)
// let writeStream = fs.createWriteStream('mpRera_Promoters.csv');
// writeStream.write(`AgentName,Agentaddress,Agenttype,Agentrera,Agentlink\n`)
const Agenturl = "http://www.rera.mp.gov.in/agentsrcg-loop.php?
show=20&pagenum=1&search_txt=&search_state=&search_dist=&search_tehs=&_=1597665284486";
var workbook = new excel.Workbook();
var worksheet = workbook.addWorksheet('MP Agents');
var worksheet2 = workbook.addWorksheet('MP Promoters');
// var arr = []
class mprera{
makeRequest(urls){
return new Promise((resolve, reject)=>{
let url = axios.get(urls);
let data = url.then((res)=>{
if (res.status==200){
resolve(res.data);
}reject("response not 200");
})
})
}
getlink(url){
return new Promise((resolve, reject)=>{
var arr = []
let soup = this.makeRequest(url);
soup.then((res)=>{
let $ = cheerio.load(res);
let table = $("#example");
let tbody = table.find("tbody");
let tr = tbody.find("tr");
for (var i = 0;i<tr.length;i++){
let td = $(tr[i]).find("td");
let link= $(td[6]).find("a").attr("href");
arr.push(link);
}
resolve (arr);
});
})
};
getAgents(url){
var link = this.getlink(url);
link.then((data)=>{
for (var i = 0;i<data.length;i++){
let soup = this.makeRequest(data[i]);
soup.then((res)=>{
let $ = cheerio.load(res);
let getDetails = $(".col-md-9").toArray();
// let name = $(getDetails[1]).text().trim();
// console.log(name);
let phone = $(getDetails[5]).text().trim();
let email = $(getDetails[6]).text().trim();
// console.log(phone, email);
writeStream.write(`${phone},${email} \n`);
})
}
})
};
}
module.exports = mprera;
My Express code:
const express = require("express");
const hbs = require("hbs");
const bodyParser = require("body-parser");
const path = require("path");
var json2csv = require('json2csv');
const mprera = require("./mprera");
let crawleer = new mprera();
const Agenturl = "http://www.rera.mp.gov.in/agentsrcg-loop.php?show=20&pagenum=1&search_txt=&search_state=&search_dist=&search_tehs=&_=1597665284486";
app = express();
//set path for views
app.set("views",path.join(__dirname,"views"))
app.set("view engine","hbs");
// for handling post requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// for public folders
app.use('/assets',express.static(__dirname + '/public'));
app.get("/", (req, res)=>{
res.render("table");
})
app.get("/mprera", async (req, res)=>{
console.log("starting");
data = await crawleer.getAgents(Agenturl);
res.attachment('filename.csv');
res.send (data);
})
app.listen(8000, ()=>{
console.log("server started");
})
crawler.getAgents needs to return a promise that doesn't resolve until after the file is written.
So something like:
crawler.getAgents = url => {
return new Promise((resolve) => {
stuff().then(() => {
// write file here
resolve()
})
})
}
I'm relatively new with mongodb and express and I wish to save data which has been retrieved via an api call, to my database. For some reason my server saves the data twice (creates two documents with same details but different id's) for a single get request and I can't figure out why
const log = console.log;
const express = require('express')
const port = process.env.PORT || 8000
const movieServer = require('./movie-getter')
const { Movie } = require('./model/Movie')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/ConspireView', { useNewUrlParser: true});
const app = express()
app.get('/movie/:name/:year', (req, res) => {
const name = req.params.name
const year = req.params.year
// let movieObject
movieServer.getMovie(name, year).then((result) => {
new Movie({
name: result.title,
year: result.release_date,
poster: result.poster_path,
banner: result.backdrop_path,
numOfDiscussions: 0,
numOfComments: 0,
vote_average: 0
// discussions: null
}).save().then(result => {
res.send(result)
})
}).catch((error) => {
log(error)
})
})
Are there any syntactic errors here?
I have the following code for handling & subscribing to the push notification on front-end which runs on port 4000:
var endpoint;
var key;
var authSecret;
// We need to convert the VAPID key to a base64 string when we subscribe
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function determineAppServerKey() {
var vapidPublicKey = 'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY';
return urlBase64ToUint8Array(vapidPublicKey);
}
export default function registerServiceWorker() {
if('serviceWorker' in navigator) {
navigator.serviceWorker.register(`${process.env.PUBLIC_URL}\sw.js`).then(function(register){
console.log("worked", register)
return register.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
// We already have a subscription, let's not add them again
return;
}
return register.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: determineAppServerKey()
})
.then(function(subscription) {
var rawKey = subscription.getKey ? subscription.getKey('p256dh') : '';
key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : '';
var rawAuthSecret = subscription.getKey ? subscription.getKey('auth') : '';
authSecret = rawAuthSecret ?
btoa(String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))) : '';
endpoint = subscription.endpoint;
alert("came here")
return fetch('http://localhost:3111/register', {
method: 'post',
headers: new Headers({
'content-type': 'application/json'
}),
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key,
authSecret: authSecret,
}),
})
});
});
}).catch(function(err){
console.log("Error",err)
})
}
}
and the server code looks like this:
const webpush = require('web-push');
const express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
const app = express();
// Express setup
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
function saveRegistrationDetails(endpoint, key, authSecret) {
// Save the users details in a DB
}
webpush.setVapidDetails(
'mailto:contact#deanhume.com',
'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY',
'p6YVD7t8HkABoez1CvVJ5bl7BnEdKUu5bSyVjyxMBh0'
);
// Home page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
// Article page
app.get('/article', function (req, res) {
res.sendFile(path.join(__dirname + '/article.html'));
});
// Register the user
app.post('/register', function (req, res) {
var endpoint = req.body.endpoint;
var authSecret = req.body.authSecret;
var key = req.body.key;
// Store the users registration details
saveRegistrationDetails(endpoint, key, authSecret);
const pushSubscription = {
endpoint: req.body.endpoint,
keys: {
auth: authSecret,
p256dh: key
}
};
var body = 'Thank you for registering';
var iconUrl = 'https://raw.githubusercontent.com/deanhume/progressive-web-apps-book/master/chapter-6/push-notifications/public/images/homescreen.png';
webpush.sendNotification(pushSubscription,
JSON.stringify({
msg: body,
url: 'https://localhost:3111',
icon: iconUrl,
type: 'register'
}))
.then(result => {
console.log("came here ")
console.log(result);
res.sendStatus(201);
})
.catch(err => {
console.log(err);
});
});
// The server
app.listen(3111, function () {
console.log('Example app listening on port 3111!')
});
server runs on 3111. When I navigate to 4000 port, I could able to see the Allow/Block pop up comes up and if I give Allow, I expect the server sends Thank you for registering messages as I have done in the server. However the Thank you for registering pop up doesn't comes up and there are no error in the console.
Note: I'm hitting 3111 by enabling CORS using chrome-extension.
I think that that could depend on your server, as i have a python server at home, and when i use the notification api it doesn't notify, unless I am on https sites. If that is not the problem then i would assume there is a code error, but I believe that you could use the broadcast channels and xhr such as : let b = new BroadcastChannel;b.onmessage(function(){XmlHTTPRequest('POST', {Data: "yes"})}; ) and use the xhr to push notifications.