I have been trying to solve this error from a long time. I could not find a similar problem online. I am sending a request through postman to twilio API for whatsapp. Everything seems ok. The promise should send a JSOM object in response but it keeps sending request until socket hangs up error occurs. Here is my code
const dotenv = require('dotenv').config();
const express = require('express');
const { response } = require('express');
const app = express();
app.use(express.json());
exports.sendMessages = function(sender, reciever, message) {
const accountSid = process.env.ACCOUNT_S_ID;
const authToken = process.env.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
from: 'whatsapp:+'+sender,
body: message,
to: 'whatsapp:+'+reciever
})
.then(response => {
return {
data: JSON.stringify(response),
}})
.catch(e => { console.error('Got an error:', e.code, e.message); });
}
Calling the API
const express = require('express');
const app = express();
app.use(express.json());
// for parsing application/json
const send = require('./index');
let endPoint = process.env.ENDPOINT;
app.post(endPoint, function (req, res) {
send.sendMessages('14155238886', '393200149462','test message');
});
const port = process.env.PORT;
app.listen(port);
console.log('Successfully connected to ' +port);
Related
Right now I have a front end react application using axios and and a backend server using node.js and express. I cannot for the life of me get my serp api data to post so that my front end can get it through axios and display the json data. I know how to get data to the front end but I am not a backend developer so this is proving to be incredibly difficult at the moment. I'm able to get the data from the the external api, I just don't know how to post it once I get it. Also I would not like to have all these request running on server.js so I created a controller but I think that is where it is messing up. Any help is appreciated
//pictures controller
const SerpApi = require('google-search-results-nodejs');
const {json} = require("express");
const search = new SerpApi.GoogleSearch("674d023b72e91fcdf3da14c730387dcbdb611f548e094bfeab2fff5bd86493fe");
const handlePictures = async (req, res) => {
const params = {
q: "Coffee",
location: "Austin, Texas, United States",
hl: "en",
gl: "us",
google_domain: "google.com"
};
const callback = function(data) {
console.log(data);
return res.send(data);
};
// Show result as JSON
search.json(params, callback);
//res.end();
}
// the above code works. how do i then post it to the server so that i can retrieve it to the backend?
module.exports = {handlePictures};
//server.js
const express = require('express');
const app = express();
const path = require('path');
const cors = require('cors');
const corsOptions = require('./config/corsOptions');
const { logger } = require('./middleware/logEvents');
const errorHandler = require('./middleware/errorHandler');
const cookieParser = require('cookie-parser');
const credentials = require('./middleware/credentials');
const PORT = process.env.PORT || 3500;
// custom middleware logger
app.use(logger);
// Handle options credentials check - before CORS!
// and fetch cookies credentials requirement
app.use(credentials);
// Cross Origin Resource Sharing
app.use(cors(corsOptions));
// built-in middleware to handle urlencoded form data
app.use(express.urlencoded({ extended: false }));
// built-in middleware for json
app.use(express.json());
//middleware for cookies
app.use(cookieParser());
//serve static files
app.use('/', express.static(path.join(__dirname, '/public')));
// routes
app.use('/', require('./routes/root'));
app.use('/pictures', require('./routes/api/pictures'));
app.all('*', (req, res) => {
res.status(404);
if (req.accepts('html')) {
res.sendFile(path.join(__dirname, 'views', '404.html'));
} else if (req.accepts('json')) {
res.json({ "error": "404 Not Found" });
} else {
res.type('txt').send("404 Not Found");
}
});
app.use(errorHandler);
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
//api/pictures.js
const picturesController= require('../../controllers/picturesController');
const express = require('express')
const router = express.Router();
// for POST request use app.post
router.route('/')
.post( async (req, res) => {
// use the controller to request external API
const response = await picturesController.handlePictures()
// send the response back to client
res.json(response)
})
module.exports = router;
You just need to return the result from SerpApi in your handlePictures function. To do this make a new Promise and when search.json runs callback do what you need with the results and pass it in resolve.
Your picturesController.js with an example of returning all results.
//pictures controller
const SerpApi = require("google-search-results-nodejs");
const { json } = require("express");
const search = new SerpApi.GoogleSearch(process.env.API_KEY); //your API key from serpapi.com
const handlePictures = async (req, res) => {
return new Promise((resolve) => {
const params = {
q: "Coffee",
location: "Austin, Texas, United States",
hl: "en",
gl: "us",
google_domain: "google.com",
};
const callback = function(data) {
resolve(data);
};
search.json(params, callback);
});
};
module.exports = { handlePictures };
Output:
And I advise you to change your API key to SerpApi to prevent it from being used by outsiders.
Since I don't have the full context of your App I can just assume the context. But given the fact that you already have wrapped the logic of calling the external API into a dedicated controller you can use it in the following way in an express app (used the hello world example from express):
// import your controller here
const express = require('express')
const app = express()
const port = 3000
// for POST request use app.post
app.get('/', async (req, res) => {
// use the controller to request external API
const response = await yourController.method()
// send the response back to client
res.json(response)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Here's an example how to execute the http request from the frontend:
const response = await fetch('http://localhost:3000') // result from res.json(response)
const express = require('express');
const app = express();
const oracle = require('oracledb');
const bodyParser = require('body-parser');
const urlEncodedBodyParser = bodyParser.urlencoded({extended:false});
app.use(bodyParser.json())
app.post("/addPlacement", urlEncodedBodyParser, function(request,response) {
console.log(request.body);
console.log(request.body.id);
/*console.log(request.body.name);
console.log(request.body.placementType);
console.log(request.body.company);
console.log(request.body.salary);
console.log(request.body.salaryType);
*/
response.send({"success": true});
});
app.listen(5050, function(err) {
if (err) {
console.log(err);
}
console.log("Server is ready to request on port 5050")
})
The console bar shows undefined when the request is being sent by the Advanced REST Client how I can solve this error?
I try to write CRUD and checking it up with Postman.
When I use a debugger at the end of the post request it's working.
Problem: When I remove the debugger and try to run the code nothing happens - only error: "Could not get any response". How can I make my post to work well without debugger?
***For example, I send this as JSON through postman like this:
{
"id":3,
"name": "Ron",
"phone": "01323133333"
}
this is the relevant code:
index.js:
const express = require('express');
const app = express();
db = require('./db');
app.use(express.static('public'));
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const port = 1400;
app.listen(port,()=>{
console.log(`Server is running on port ${port}`);
})
//post request:
app.post('/user' , (req,res)=> {
const {body} = req,
{id,name,phone} = body
db.query(`INSERT INTO public.users(
id, name, phone)
VALUES (${id}, '${name}', '${phone}');`,(err,dbRes)=>{
if(err)
res.status(400).send(err);
else
{
res.send(dbRes.rows);
}
})
})
db.js:
const {Client} = require ('pg');
const client = new Client ({
user:'postgres',
host:'localhost',
database:'nodeapp',
password:'123456',
port:5432
})
client.connect();
module.exports = client;
Thank you !
i am trying to send a list containing info from a form to mailchimp server,it requires a basic http authentication. When i am sending the request using curl i am able to retrieve the page, but when i run the local sever it is showing socket errors.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public/"));
app.get("/",function(req,res){
res.sendFile(__dirname+"/signup.html");
});
app.post("/",function(req,res){
console.log(req.body);
const fn = req.body.fn;
const sn = req.body.ln;
const mail = req.body.mailid;
const data ={
members: [
{
email_address: mail,
status: "subscribed",
merge_fields: {
FNAME : fn,
LNAME :sn
}
}
]
};
var url = "https://us4.api.mailchimp.com/3.0/lists/*listid*";
var jsonData = JSON.stringify(data);
var options ={
method: "POST",
auth:"*username*:*key*"
};
const request = https.request(url,options,function(response){
response.on("d",function(d){
console.log(JSON.parse(d));
});
request.write(jsonData);
request.end();
});
});
app.listen(3000,function(){
console.log("at 3000");
});
i am getting the following
error
Try to change
response.on("d",function(d){
console.log(JSON.parse(d));
});
to
response.on("data",function(d){
console.log(JSON.parse(d));
});
and make sure to end the request by specifying request.end();. Otherwise it will not stop posting to the server you have to end posting.
I tried many times but am getting the following error
http://localhost:3001/getLocaiton net::ERR_CONNECTION_REFUSED and
createError (createError.js:17) at XMLHttpRequest.handleError
(xhr.js:87.
How can I solve this issue.
axios.post ('http://localhost:3001/getLocaiton' , {
name: keyWord,
})
.then (function (response){
console.log (response);
})
.catch (function (error){
console.log (error)
});
Following is the code for node back-end
const express = require ('express');
const bodyParser = require ('body-parser');
const cors = require ('cors');
const Client = require('node-rest-client').Client;
const client = new Client ();
const http = require('http')
const app = express ();
app.use(cors())
app.use (bodyParser.urlencoded ({extended :false}))
app.use(bodyParser.json());
const server = http.createServer(app)
server.listen(port)
app.post ('/getLocaiton' , (req, res) =>{
const typeWord = req.body.name;
client.get ('https://api.adform.com/v1/help/buyer/advertisers= '+typeWord+"&key=", function (data, response){
console.log (data);
console.log (response);
})
})
app.listen (3001, ()=> {
console.log ("listining to port 3001")
})
I do not know why you are starting two servers instances by listening on two ports, but I commented out first port listening and you must return respond to your /getLocaiton request (by the way there is a typo in path name):
const express = require ('express');
const bodyParser = require ('body-parser');
const cors = require ('cors');
const Client = require('node-rest-client').Client;
const client = new Client ();
const http = require('http')
const app = express ();
app.use(cors())
app.use (bodyParser.urlencoded ({extended :false}))
app.use(bodyParser.json());
// const server = http.createServer(app)
// server.listen(port)
app.post ('/getLocaiton' , (req, res) =>{
const typeWord = req.body.name;
client.get('https://api.adform.com/v1/help/buyer/advertisers='+
typeWord+
"&key=",function (data, response){
console.log (data);
console.log (response);
// you must return your response to your request
res.json({
data: data
})
}
)
})
app.listen (3001, ()=> {
console.log ("listining to port 3001")
})