I am trying to make a simple application which tries to send an SMS. I am using Axios to send a request to the server to send the SMS, and I am using Node.js for the server.
Below given is a snippet of the code of App.js sending the request to server, with parameter NUM which contains the number that twilio (SMS Service) has to send an SMS to
const sendSMSClinic = async () => {
console.log("CLINIC SMS SENDING FUNCTION ACCESSED");
try {
let res = await axios.get("http://localhost:3001/api/mail", {params: {
NUM: "971561490375"
}});
} catch(AxiosError) {
console.log(AxiosError)
}
}
Below given is the code of index.js which initiates the node.js server and tries to send an SMS
const express = require('express');
const app = express();
const port = process.env.PORT || 3001;
var cors = require('cors')
app.use(cors())
const accountSid = 'AC8ae163a17e6e3d2ce63e64a98bac68c4';
const authToken = '0a13cc33147e4ffb34682097fbf6c49d';
const client = require('twilio')(accountSid, authToken);
app.get('/api/mail/:NUM', async (req, res) => {
console.log(req.params.NUM);
client.messages
.create({
to: '+971561490375',
from: '+16188160866',
body: 'REASON FOR CALL: CLINIC EMERGENCY'
})
.then(message => console.log(message.sid))
.done();
})
app.get("/",(req,res)=>{
res.status(200).send("successful")
})
app.listen(port, () => {
console.log('Server is up and running on port ', port);
})
The problem is that I am getting the below errors
GET http://localhost:3001/api/mail?NUM=971561490375 404 (Not Found)
and
AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
You should change your axios request to:
const num = "971561490375";
const res = await axios.get(`http://localhost:3001/api/mail/${num}`)
If you want to add multiple path parameters you can edit your end-point declaration to:
app.get('/api/mail/:NUM/:NUM2', (req, res) => {
console.log(req.params.NUM, req.params.NUM2);
...
}
And your axios request to:
const num = "971561490375";
const num2 = "971561490375";
const res = await axios.get(`http://localhost:3001/api/mail/${num}/${num2}`);
Related
I wrote the following code for parse some part of HTML for one URL. I means parse page const URL= 'https://www.example.com/1'
Now I want to parse the next page 'https://www.example.com/2' and so on. so I want to implement a For-Loop manner here.
what is the easiest way that I can use the iteration manner here to
change URL (cover page 1,2,3, ...) automatically and run this code in repeat to parse other pages? How I can use for-loop manner here?
const PORT = 8000
const axios = require('axios')
const cheerio = require('cheerio')
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
const url = 'https://www.example.com/1'
app.get('/', function (req, res) {
res.json('This is my parser')
})
app.get('/results', (req, res) => {
axios(url)
.then(response => {
const html = response.data
const $ = cheerio.load(html)
const articles = []
$('.fc-item__title', html).each(function () {
const title = $(this).text()
const url = $(this).find('a').attr('href')
articles.push({
title,
url
})
})
res.json(articles)
}).catch(err => console.log(err))
})
app.listen(PORT, () => console.log(`server running on PORT ${PORT}`))
Some considerations, if you added CORS to your app, so that you can GET the data, it's useless, you add CORS when you want to SEND data, when your app is going to receive requests, CORS enable other people to use your app, it's useless then trying to use other people's app. And CORS problems happen only in the browser, as node is on the server, it will never get CORS error.
The first problem with your code, is that https://www.example.com/1, even working on the browser, returns 404 Not Found Error to axios, because this page really doesn't exist, only https://www.example.com would work.
I added an example using the comic site https://xkcd.com/ that accepts pages.
I added each axios request to an array of promises, then used Promise.all to wait for all of them:
The code is to get the image link:
const PORT = 8000;
const axios = require("axios");
const cheerio = require("cheerio");
const express = require("express");
const app = express();
const url = "https://xkcd.com/";
app.get("/", function (req, res) {
res.json("This is my parser");
});
let pagesToScrap = 50;
app.get("/results", (req, res) => {
const promisesArray = [];
for (let pageNumber = 1; pageNumber <= pagesToScrap; pageNumber++) {
let promise = new Promise((resolve, reject) => {
axios(url + pageNumber)
.then((response) => {
const $ = cheerio.load(response.data);
let result = $("#transcript").prev().html();
resolve(result);
})
.catch((err) => reject(err));
});
promisesArray.push(promise);
}
Promise.all(promisesArray)
.then((result) => res.json(result))
.catch((err) => {
res.json(err);
});
});
app.listen(PORT, () => console.log(`server running on PORT ${PORT}`));
I have a frontend JS script that takes text input from an HTML text box and sends it to an expressjs server. The body of the POST request, though, is always undefined, or depending on how I tweak things, returning as "{ }" if I view it via console.log( ). As I'm new to this, I can't seem to see what's going wrong.
Front end js:
async function submitCity(){
let x = document.getElementById("wg_input").value;
console.log("Successfully captured city name:", x);
let toWeather = JSON.stringify(x);
console.log("Input data successfully converted to JSON string:", toWeather);
const options = {
method: 'POST',
mode: 'cors',
headers: {'Content-Type': 'text/plain'},
body: toWeather
}
fetch('http://localhost:3000', options)
.then(res => console.log(res))
.catch(error => console.log(error))
}
Backend:
// Dependencies
const express = require('express');
const bp = require("body-parser");
const request = require("request");
const jimp = require('jimp');
const cors = require('cors');
const wgServer = express();
const port = 3000;
// Dotenv package
require("dotenv").config();
// OpenWeatherMap API_KEY
const apiKey = `${process.env.API_KEY}`;
// Basic server initialization
wgServer.use(cors())
wgServer.use(bp.json())
wgServer.use(bp.urlencoded({ extended: true }))
wgServer.listen(port, function() {
console.log(`Example app listening on port ${port}!`)
});
wgServer.post('/', async function (req, res) {
res.set('Content-Type', 'text/plain');
console.log(req.body)
res.send('Hello World');
//const data = await req.body;
// let jsonData = JSON.stringify(req.body);
// res.status(201);
//res.json();
});
The returned data is supposed to be a string of about 15 characters, give or take a few (a city and state). I thank you in advance.
I have a node js application where I forward form data from the client to the server to store this data there in a mongoDB.
To send the data to the server I use a POST request with API_URL: http://localhost/mews.
Whenever the POST request is executed, I keep seeing a CORS error in the console of the client.
client side JS
const API_URL = "http://localhost/mews";
form.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
//Grab the form values
const name = formData.get('name');
const content = formData.get('content');
const mew = {
name,
content
}
//send the mew information to the server
const response = await fetch(API_URL, {
method: "POST",
body: JSON.stringify(mew),
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log(json);
});
server side JS
const express = require('express');
const cors = require('cors');
const db = require('monk')('localhost/meower');
const mewe = db.get('mews');
var corsOptions = {
origin: 'http://localhost/mews',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
const app = express();
app.use(cors(corsOptions));
app.use(express.json());
function isValidMew(mew) {
return mew.name && mew.name.toString().trim() !== '' &&
mew.content && mew.content.toString().trim() !== '';
}
//chen user sends a message (POST)
app.post('/mews', async (req, res) => {
if (isValidMew(req.body)) {
const mew = {
name: req.body.name.toString(),
content: req.body.content.toString(),
created: new Date()
};
console.log(mew);
const createdMew = await mewe.insert(mew);
res.json(createdMew);
} else {
res.status(422);
res.json({
message: 'Hey! Name and Content are required!'
});
}
});
app.listen(4000, () => {
console.log("Listening on http://localhost:4000/");
});
ERROR in client console when making the post request
Cross-Origin Request Blocked: The Same Origin Policy does not allow reading of the remote resource at http: // localhost / mews. (Reason: CORS request was unsuccessful).
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
this worked for me using "cors": "2.8.5"
const express = require('express');
const cors = require('cors');
const db = require('monk')('localhost/meower');
const mewe = db.get('mews');
const app = express();
app.use(express.json());
app.use(cors());
Hope it helps you too, the reference is in here https://www.npmjs.com/package/cors
I'm trying to connect from Nodejs to DialogFlow. I have completed all the steps to configure the user agent, the intent, etc. If I lunch with NODEMON the app, all its ok, but when I send a GET or POST request I get this error:
"UnhandledPromiseRejectionWarning: TypeError: sessionClient.projectAgentSessionPath" and more. But I think the most relevant mistake is this.
The code I used it's the same as the APi docs. I don't know why I get this error.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const dialogflow = require('#google-cloud/dialogflow');
const uuid = require('uuid');
//const sendReq = require('./reqDialogFlow');
async function runSample(projectId = 'helpcenter-qwoj') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
console.log(sessionPath);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hello',
// The language used by the client (en-US)
languageCode: 'it',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
};
app.get('/', (req, res) => {
res.send({ "hello": "Daniele Asteggiante" })
});
app.post('/api/textAPIE', (req, res) => {
res.send({ "text": "CIAO" });
runSample();
});
app.use(bodyParser.json());
const PORT = process.env.PORT || 5000;
app.listen(PORT);
i had the same error.
i had installed
npm i dialogflow
instead of
npm install #google-cloud/dialogflow
I tried to change the Express Version version with an earlier version 4.17.0 instead 4.17.1.
Now it goes.
change "sessionClient.projectAgentSessionPath" -> "sessionClient.sessionPath"
Found this solution on github:https://github.com/googleapis/nodejs-dialogflow/issues/127
I am trying to built a local server for dialogflow bot using a node.js framework but ,not able to establish one .
I am using serveo.net as tunneling as ngrok doesn't work as it is blocked by my institute.
I am able to launch a server but unable to get a response from it back to the dialogflow agent.
'use strict';
const {WebhookClient} = require('dialogflow-fulfillment');
const express = require("express"); //express
const bodyParser = require("body-parser"); //body-parser
const app = express(); //app
app.use(bodyParser.json);
app.use(bodyParser.urlencoded({
extended: true
})
);
const WEBHOOK = 'webhook';
app.get('/', (req, res) => res.send('online'));
app.post('/webhook', express.json(), (request, respond) => {
const agent = new WebhookClient({
request,
response
});
function webhookprocessing(request, response) {
const agent = new WebhookClient(request, response);
const action = agent.intent;
if (action == WEBHOOK) {
agent.add("My name is karthik");
} else {
agent.add("karthik");
}
}
function welcome() {
agent.add('Welcome to my agent!')
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set("webhook", webhookprocessing);
agent.handleRequest(intentMap)
//const agentPath = agent.entitiesClient.projectAgentPath("master-bot-53dee");
//console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
//console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
//console.log("Server Hit");
});
app.listen(process.env.PORT || 5000);
edit1: I am getting a request from google dialogflow but my local server isn't sending a response.
edit2: The response payload shown received by dialogflow from my node is
{
"responseId":"efaf7898-74de-4727-bf2a-8eeb32ba570a-baaf0c1f",
"queryResult":{
"queryText":"1",
"parameters":{
"number":1
},
"allRequiredParamsPresent":true,
"fulfillmentMessages":[
{
"text":{
"text":[
""
]
}
}
],
"intent":{
"name":"projects/master-bot-53dee/agent/intents/15b96d92-4adb-4657-8b15-ebdf7df180b4",
"displayName":"webhook"
},
"intentDetectionConfidence":1,
"diagnosticInfo":{
"webhook_latency_ms":4991
},
"languageCode":"en"
},
"webhookStatus":{
"code":4,
"message":"Webhook call failed. Error: Request timeout."
}
}
and the request payload send by dialogflow is
{
"responseId":"efaf7898-74de-4727-bf2a-8eeb32ba570a-baaf0c1f",
"queryResult":{
"queryText":"1",
"parameters":{
"number":1
},
"allRequiredParamsPresent":true,
"fulfillmentMessages":[
{
"text":{
"text":[
""
]
}
}
],
"intent":{
"name":"projects/master-bot-53dee/agent/intents/15b96d92-4adb-4657-8b15-ebdf7df180b4",
"displayName":"webhook"
},
"intentDetectionConfidence":1,
"languageCode":"en"
},
"originalDetectIntentRequest":{
"payload":{
}
},
"session":"projects/master-bot-53dee/agent/sessions/d1205a66-9eda-d79c-7677-75eeb402e7e5"
}
The request sent by dialogflow reaches my public url created by my tunneling software but there isn't any response from the localhost .
This image is a screenshot of my console where I appear to be getting a post request but there isn't a response appearing on dialogflow.
I have used this url to refer webhook url https://excedo.serveo.net/.
app.post('/webhook', express.json(), (request, respond) => { // error name of the param doesn't match its usage
This line you are using respond as the parameter and passing and using response instead .Please change line to -
app.post('/webhook', express.json(), (request, response) => {
The webhook isn't being called at the /webhook path because the configuration in Dialogflow is telling it the webhook is at /. If you change this to https://excedo.serveo.net/webhook it will be routed correctly.