I'm using Slack Bolt Framework with Javascript and I'm trying to do a http request. The problem is that the code is not waiting the request to be finished even using async/await. It always gives 'undefined'
The endpoint I'm requesting is 'https://viacep.com.br/ws/' + cep + '/json/' where cep is a parameter set by the user (like 09784100 for instance).
Here is the code that call the http request function:
// Action listener function called when an interactive component with action_id of “submitCEPButton” is triggered
app.action('submitCEPButton', async ({ ack, body, client, say, text}) => {
// Acknowledge action request before anything else
await ack();
let channelID = body.channel.id
let userID = body.user.id
var cep = body.state.values['inputBlock']['inputCEP'].value
if(isValidCep(cep)){
//console.log('É valido');
let data = await getAddressData(cep);
console.log(data);
await say({
"blocks": [
{
"type": "header",
"block_id": "headerBlock",
"text": {
"type": "plain_text",
"text": "🔍 Busca de Endereço - Resultado",
"emoji": true
}
},
{
"type": "divider",
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Rua: * " + data.logradouro
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Complemento: * " + data.complemento
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Bairro: * " + data.bairro
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Cidade: * " + data.localidade
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Estado: * " + data.uf
}
}
]
})
}
else{
await client.chat.postEphemeral({
channel: channelID,
user: userID,
text: `<#${userID}> ❌ CEP inválido. Verifique o CEP digitado e tente novamente.`
});
}
});
And here is the code that make the http request:
//Make http request
async function getAddressData(cep){
var url = 'https://viacep.com.br/ws/' + cep + '/json/';
let data = '';
https.get(url, res =>{
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
data = JSON.parse(data);
//return data;
})
})
return data;
}
You're mixing async models between callbacks and async/await methodology. Instead, try this (using superagent, which has async native mechanisms, to simplify the code I'm writing):
const superagent = require('superagent');
async function getAddressData(cep){
const url = 'https://viacep.com.br/ws/' + cep + '/json/';
const response = await superagent.get(url);
return response.body;
}
As an alternative, you could also use a Promise if you want to stick with vanilla Javascript HTTP Request.
Related
I am trying to GET an event by its id but for some reason i am getting an empty array as result in postman.
This is my route:
import { events } from '../../../db.json';
const handler = async (req , res) => {
const evt = events.filter( (ev) => ev.id === req.query.id );
if(req.method === 'GET'){
return res.status(201).json(evt);
}
return res.status(400).json({ error: 'Event not found' });
}
export default handler;
This is my db.json:
{
"events": [
{
"id": 1,
"title": "Recital coldplay",
"description": "Recital de coldplay en River"
},
{
"title": "Recital metalica",
"description": "Recital de metalica en velez",
"id": 2
},
{
"title": "asdasd",
"description": "asdasdsa",
"id": 3
},
{
"title": "Dave Chappel Standup",
"description": "Dave Chappel standup comedy",
"id": 4
},
{
"title": "test",
"description": "teeesest",
"id": 5
}
]
}
the route is api/events/[id]
Any reason why if in postman i enter a GET route with te following api/events/1 instead of showing the first event data i get []?
You can use req.params.id if your route looks like api/events/:id
If you want to use req.query you can add query parameters like this:
api/events?id=1
// with req.param (api/events/1)
app.get("/api/events/:id", (req, res) => {
const evt = events.filter((ev) => ev.id === req.params.id);
res.json(evt);
});
// with req.query (api/events?id=1)
app.get("/api/events", (req, res) => {
const evt = events.filter((ev) => ev.id === req.query.id);
res.json(evt);
});
So i managed to get username from a link but im unsure of how to actually get the userid back.
I want it so when it to say the username which works perfectly, but down in thumbnail when i try to fetch the userId it comes up as "userId is not defined".
I'm it sure what the solution is but I want to keep both userId and username.
here is my code!
const getUsername = userId => new Promise(resolve => {
fetch('https://users.roblox.com/v1/users/' + userId)
.then(res => res.json())
.then(body => resolve(body.name || 'Unknown'))
.catch(() => resolve('Unknown'))
})
(async () => {
const username = await getUsername(nextInQueue.offers[0].userId);
consola.success(`[${username}] has ok items`)
fetch(config.webhook, {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
"content": null,
"embeds": [
{
"title": ":tada: Trade sent to: " + username + " :tada:",
"color": 28420,
"fields": [
{
"name": "Cool Items:",
"value": itemNameList.join('\n')
},
{
"name": "Okay items:",
"value": toreceiveList.join('\n')
}
],
"author": {
"name": "Expoorttoo",
"icon_url": "https://i.pinimg.com/736x/4b/69/74/4b6974aef5d96580140ef2686072af3f.jpg"
},
"footer": {
"text": Sentto.toLocaleString() + " sent & " + tradeQueue.length.toLocaleString() + " set in queue"
},
"thumbnail": {
"url": "https://www.roblox.com/headshot-thumbnail/image?userId=" + userId + "&width=420&height=420&format=png"
}
}
]
})
})
})().catch();
}
oh yeah by the way its a webhook which it sends to on discord. It works without thumbnail but doesnt work with the thumbnail saying userid.
You are missing
const userId = nextInQueue.offers[0].userId;
I want to implement paypal to my website, but I am stuck with this. Always when I try to do a post request (also tried with postman), I dont get an answer which is just the normal 404 error-page. The console is showing no error, so I guess the post request is not getting recognized.
What could be the problem and how can I fix it?
server.js
//payment
app.post("/pay", (req, res) => {
// payment data
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/success",
"cancel_url": "http://localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "product1",
"sku": "001",
"price": "350.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "350.00"
},
"description": "test"
}]
};
// create payment
paypal.payment.create(create_payment_json, (error, payment) => {
if(error) {
console.log("payment not successful");
console.log(error)
} else {
console.log("payment successful");
console.log(payment);
}
})
})
products.ejs
<form action="/pay" method="post">
<input type="submit" value="add to cart" onclick="window.location.href='/pay'"/>
</form>
Couple of things you need to make sure
Make sure you are sending the post request to the correct port, just incase your express server isn't hosting the actual site as well. If it is then don't worry about the port
You can use js to send the request to prevent the page from refreshing.
const form = document.querySelector('form')
form.addEventListener('submit', async function(e) {
e.preventDefault()
const port = 3000 //make sure this is the port your express erver is listening on
const formData = new FormData(e.target)
const itemId = formData.get('itemId')// You can store the items id in the name attribute of an input
const response = await fetch(`http://localhost:${port}/pay`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({itemId})
})
})
const data = await response.json()
console.log(data) // The response you would get from the server
I'm trying to code a Hubot listener that would automatically create a JIRA issue from a specific chat dialogue. Here's the example (I used Hubot-Rocketchat boilerplate code from here: https://github.com/RocketChat/hubot-rocketchat-boilerplate)
module.exports = (robot) => {
robot.hear(/^#alerts (.*)/i, (res) => {
const jiraurl="https://jira.example.com/rest/api/2/issue/"
const jiraproject="ALERTS"
text = res.match[1]
data = JSON.stringify({
"fields": {
"project":
{
"key": `#{jiraproject}`
},
"summary": `#{text}`,
"description": "Задача создана автоматически из RocketChat",
"issuetype": {
"name": "Инцидент"
}
}
})
/* res.reply(data) */
res.reply(`Создаю задачу в JIRA: ${text}`)
robot.http(jiraurl)
.header('Content-Type', 'application/json')
.post(data) (err, response, body) =>
if err
res.send `Ошибка: #{err}`
return
})
}
What would be the proper way to do this?
I am creating an application in which I want to use some data from a JSON, which is generated by another js file. Here is the code which is generating JSON
var request = require('request');
module.exports = {
foo:
request('https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/c1d1e5d6-fe5c-42de-8713-60f272a3b63e?subscription-key=d3d3e4dfa8744be9b4ae47558df8fc5a&timezoneOffset=0&verbose=true&q=hey',function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log(body);
})
};
I am interested in body object, which is giving following contents -
{
"query": "hey",
"topScoringIntent": {
"intent": "Help",
"score": 0.500165462
},
"intents": [
{
"intent": "Help",
"score": 0.500165462
},
{
"intent": "None",
"score": 0.10364107
},
{
"intent": "SearchHotels",
"score": 0.00249445555
},
{
"intent": "ShowHotelsReviews",
"score": 9.451727E-06
}
],
"entities": []
}
Now I want to access value of intent from topScoringIntent element. That to in another JS file. I tried using body[1].intend but it gives undefined.
I am very new to javascript and need very basic code to do this. Please give some suggestions on this. Also plz tell me if this can be solved by body-parser and if yes then how?
Update - Here is the code where I want to use body['topScoringIntent'].intent as global.
require('dotenv-extended').load();
var builder = require('botbuilder');
var restify = require('restify');
var Store = require('./store');
var spellService = require('./spell-service');
var request = require('request');
var myJSON = require("JSON");
var fs = require('fs');
//var window = window;
var request = require("request");
var myJSON = require("JSON");
var globalVar = [];
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create connector and listen for messages
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
function getMyBody(url, callback) {
request({
url: 'https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/c1d1e5d6-fe5c-42de-8713-60f272a3b63e?subscription-key=d3d3e4dfa8744be9b4ae47558df8fc5a&timezoneOffset=0&verbose=true&q=hey',
json: true
}, function (error, response, body) {
if (error || response.statusCode !== 200) {
return callback(error || {statusCode: response.statusCode});
}
global.topScoringIntent = body['topScoringIntent'].intent;
//if(body['topScoringIntent'].intent == 'Help');
//console.log('yay');
callback(null, body);
});
}
getMyBody('https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/c1d1e5d6-fe5c-42de-8713-60f272a3b63e?subscription-key=d3d3e4dfa8744be9b4ae47558df8fc5a&timezoneOffset=0&verbose=true&q=hey', function(err, body) {
if (err) {
console.log(err);
}
})
if(body['topScoringIntent'].intent == 'Help');
console.log('success');
This should work for you
console.log(response.topScoringIntent.intent);
body.topScoringIntent.intent will return 'Help'.
To use it globally you can set a var :
var body = {
"query": "hey",
"topScoringIntent": {
"intent": "Help",
"score": 0.500165462
},
"intents": [
{
"intent": "Help",
"score": 0.500165462
},
{
"intent": "None",
"score": 0.10364107
},
{
"intent": "SearchHotels",
"score": 0.00249445555
},
{
"intent": "ShowHotelsReviews",
"score": 9.451727E-06
}
],
"entities": []
}
var result = body.topScoringIntent.intent;
And then use result somewhere else :
console.log(result);