How can I POST REST API using React JS and Node JS - node.js

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")
})

Related

Express JS app showing cannot find after deployment on cPanel while working fine on local

Express App showing cannot find after deploying on cPanel. I have tried to sort out this issue also when I write server.listen() it works great but when I write app.listen() it gives cannot find message.
I tried default Node Js code (last 10 lines except app.listen() ) which works fine while app.listen() not working:
const express = require("express");
const multiparty = require('multiparty');
const mongoose = require("mongoose");
const morgan = require('morgan');
const { createHttpTerminator } = require('http-terminator');
const fs = require('fs');
const cors = require('cors');
const crypto = require('crypto');
require('dotenv').config();
const { MongoClient, ServerApiVersion } = require('mongodb');
const {Product, Service, Home, HireMe } = require('./models/Product');
const app = express();
app.use(morgan('tiny'));
app.use(express.static('public'));
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Home Page...!');
});
app.get('/offers', async (req, res) => {
try {
const result = await Product.find({});
res.send("result");
} catch (err) {
res.send({ 'error': err.message });
}
})
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(app);
});
server.listen(); //It works
app.listen (); // Showing Cannot find message
I solved this error by prefixing the URL link (on which I created node JS on cPanel) to routes. Now it works great.

Request body is undefined when the request is sent through the ARC in express

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?

twilio API keeps sending request until socket hangs up error occurs

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);

axios first request succeeds second request fails

i have a simple node node express server in which i get data from an api,it works fine on the first request but fails when i try to make a second request
const express=require("express");
const axios =require("axios");
const cors = require('cors');
const app=express();
app.use(cors());
app.get("/devices",(req,res)=>{
axios.get(
'http://ipaddress/api/reports',
).then((response) => {
res.status(200);
res.json(response.data);
}).catch((error) => {
res.status(400)
res.send("error")
});
});
app.listen(3002,()=>{
console.log("started on port 3002");
});
The problem i found here is you have initialize the server in your get route. The app.listen.. code should be outside the get route implementation. I doubt if your code even runs for the first time. Change your code like:
const express = require("express");
const axios = require("axios");
const cors = require('cors');
const app = express();
app.use(cors());
app.get("/devices", (req,res) => {
axios.get(
'http://ipaddress/api/reports',
).then((response) => {
res.status(200).json(response.data);
}).catch((error) => {
res.status(400).send("error")
});
});
app.listen(3002,() => {
console.log("started on port 3002");
});
Hope this helps :)

Can Not POST NodeJS Express

I was trying to make an axios post request to an express server and I receive that Error: Request failed with status code 404 at createError. Postman says Can Not POST. I don't know what could be wrong, i'm new in all this, so all the help it's good, thanks.
Axios and Express server are from 2 different link. They are google cloud function.
Thanks for the help
Axios Post Request :
exports.notification = (req, res) => {
var axios = require('axios');
var https = require('https');
var bodyParser = require('body-parser');
var config = {
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Type' : 'text/html',
'Content-Type' : 'application/json' }
};
var info = {
ids:[req.body.id,req.body.id1],
type: req.body.type,
event: req.body.action,
subscription_id: req.body.subid,
secret_field_1:null,
secret_field_2:null,
updated_attributes:{
field_name:[req.body.oname,req.body.nname]}
};
var myJSON = JSON.stringify(info);
return axios.post('https://us-central1-copper-mock.cloudfunctions.net/api/notification-example', myJSON)
.then((result) => {
console.log("DONE",result);
})
.catch((err) => {
console.log("ERROR",err);
console.log("Error response:");
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
})
};
Express Server
const express = require ('express');
const https = require ('https');
const bodyParser = require ('body-parser');
const app = express();
const port = 8080;
// ROUTES
var router = express.Router(); // get an instance of router
router.use(function(req, res, next) { // route middleware that will happen on every request
console.log(req.method, req.url); // log each request to the console
next(); // continue doing what we were doing and go to the route
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/',require ('./Routers/API/home'));
app.use('/leads',require ('./Routers/API/leads'));
app.use('/people',require ('./Routers/API/people'));
app.use('/companies',require ('./Routers/API/companies'));
app.use('/opportunities',require ('./Routers/API/opportunities'));
app.use('/projects',require ('./Routers/API/projects'));
app.use('/tasks',require ('./Routers/API/tasks'));
app.use('/activities',require ('./Routers/API/activities'));
app.use('/notification-example',require ('./Routers/API/notification_example'));
app.use('/', router); // apply the routes to our application
// START THE SERVER
// ==============================================
app.listen(port);
console.log('Listening ' + port);
module.exports={
app
};
Notification Route
const express = require('express');
const router = express.Router();
//const notification_example = require('../../Notification');
router.get('/', function(req, res) {
console.log('DATA',JSON.parse(res.data));
console.log('BODY',JSON.parse(res.body));
});
module.exports = router;

Resources