How to Make API calls in express server - node.js

I am trying to make a get request in an express server, currently the server simply prints all post requests and it works fine up to that, the issue is when GET request is made the response is returned as 'undefined'
var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const hostname = config.server.host;
const port = config.server.port;
app.post("/", (req, res) => {
console.log(req.body);
res.sendStatus(200);
axios
.get("https://reqres.in/api/products/3")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});
});
app.listen(port, hostname, () =>
console.log(`Server running at http://${hostname}:${port}/`)
);

Use Postman to send Api calls to the server. I am attaching the link down below.
Install Postman chrome extension, if you're using chrome.
Use the Localhost:port server and post method and add variable to post your query
Hope this helps.
Moreover, Just add this tweak in your code and listen on a proper localhost,
var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const hostname = config.server.host;
const port = config.server.port;
app.post("/", (req, res) => {
console.log(req.body);
res.sendStatus(200);
axios
.get("https://reqres.in/api/products/3")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});
});
app.listen(1337, function(){
console.log('Express listening on port', this.address().port);
});

Executed the below code
axios .get("https://reqres.in/api/products/3")
.then(response => { console.log(response); })
.catch(error => { console.log(error.response); })
Its executed and working fine.
My Guess is that in your case its going to catch block
Change the following line
.catch(error => {
console.log(error.response);
});
TO
.catch(error => {
console.log(error);
});
And see whether some error is printing.No response object is assigned to error, that may be u r receiving undefined

Related

Node Express how to edit the app.post url

I have a simple example of Google App Script sending a post request to my Node application. This is working perfectly.
GAS
function send_webhook_test() {
const url = 'http://my.ip.address/folder'
var body = {msg:'hello from gas'}
var params = {
'method': 'post',
'muteHttpExceptions': true,
'contentType': 'application/json',
'payload':JSON.stringify(body)
};
var res = UrlFetchApp.fetch(url, params);
console.log(res)
}
Node
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
const PORT = 3000
const path = require('path');
app.use(bodyParser.json())
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.post('/', (req, res) => {
console.log(req)
console.log(req.body)
res.status(200).end()
})
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
I would like to change the app.post from ('/') to ('someValue'). So I make the following edit:
GAS
const url = 'http://my.ip.address/folder/someValue'
Node
app.post('/someValue', (req, res) => {
console.log(req)
console.log(req.body)
res.status(200).end()
})
But this returns the error Cannot POST //someValue. How do I correctly change the post url?
Your request is adding a '/'char before the /someValue route.
You can use a middleware to sanitize the path before searching for the routes, or you can review your GAS code to remove the duplicated '/'

nodejs reachable from internet via react application

I have a react app running on https and a nodejs running localhost:3001. my nodejs app does not capture data from react application.
What have I missed?
server.js (Nodejs)
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();
const Excel = require('exceljs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());
app.get('/', ()=>{
console.log('welcome to test')
})
app.post('/api/xcl', (req, res) =>{
const workbook = new Excel.Workbook();
workbook.xlsx.readFile('test.xlsx')
.then(() =>{
const workSheet = workbook.getWorksheet('test');
workSheet.addRow([req.body.fNamn, req.body.eNamn, req.body.oNamn, req.body.ePost,
req.body.dVal, req.body.kNamn]);
workbook.xlsx.writeFile('test.xlsx');
})
.catch(error => {
console.log(error.message);
});
const PORT = process.env.PORT || 3001
app.listen(PORT, () => console.info(`server has started on ${PORT}`))
app.js (Reactjs)
axios.post('http://localhost/:3001/api/xcl', data)
.then(res =>{
setSent(true)
console.log(res.data)
})
.catch(() => {
console.log(err=>console.log(err.response.data));
})
I have declared the proxy "proxy": "http://localhost:3001/" in package.json
React app runs on an iis site https://test.me:443
If you have set proxy, you don't need to write http://localhost:3001 in your http request, try
axios.post('/api/xcl', data)
.then(res =>{
setSent(true)
console.log(res.data)
})
.catch(() => {
console.log(err=>console.log(err.response.data));
})
There is another way.
You can create your axios instance, and give it baseURL, then for
http calls use that instance of axios.
import axios from "axios";
const api = axios.create({
baseURL: "http://localhost:3001",
});
api.post('/api/xcl', data)
.then(res =>{
setSent(true)
console.log(res.data)
})
.catch(() => {
console.log(err=>console.log(err.response.data));
})

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

React gives me Cannot GET / page_name While reloading (node/express)

I am trying to build a reactjs app and I am trying to pass data through from my front end (react) to my backend (node/express). However I am getting an error when I try and view the page I get this error. (Cannot GET /home).
const express = require("express");
const app = express();
const port = 5000;
const cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
bodyParser.urlencoded({
// to support URL-encoded bodies
extended: true
})
);
app.post("/home", (req, res) => {
const data = [(generalDetail = req.body.generalDetail)];
console.log(generalDetail, "has been added to /home");
res.json(data);
});
app.listen(port, () => `Server running on port ${port}`);
here is my onSubmit function:
onSubmitForm = e => {
e.preventDefault();
let data = {
generalDetail: this.state.generalDetails,
firstName: this.state.firstName,
middleName: this.state.middleName,
lastName: this.state.lastName
};
axios.post("http://localhost:5000/home", data).then(() => {
//do something
}).catch(() => {
console.log("Something went wrong. Plase try again later");
});
You dont have a get route for home, that is why you are having trouble.
Add the following code above your post route.
app.get("/home", (req, res) => {
console.log("here");
});

Can't use axios to get/post data from/to localhost server in android 7.0 device - React Native app

I use Axios in my react native app. I use Mobiistar Zumbo J2 with Expo to test but I get err: Network Error. I also set CORS for my node server but it still doesn't work. I test with Postman it work normally. Here is my code:
server.js
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const index = require("./routes/index");
const bookings = require("./routes/bookings");
const cors = require('cors'); // Yep, you need to install this
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.listen(port, () => {
console.log('Server is running on port', port);
});
app.set("views", path.join(__dirname, "views"));
app.set("view engine", 'ejs');
app.engine("html", require("ejs").renderFile);
//Body parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//Routes
app.use("/", index);
app.use("/api", bookings);
bookings.js
const express = require("express");
const router = express.Router();
const mongojs = require("mongojs");
const db = mongojs("mongodb://<username>:<password>#ds139614.mlab.com:39614/booking-car-app", ["bookings"]);
router.get("/bookings", (req, res, next) => {
db.bookings.find((err, data) => {
if (err) {
res.send(err);
}
res.json(data);
});
});
router.post("/bookings", (req, res, next) => {
const booking = req.body;
if (!booking.userName) {
res.status(400);
res.json({err: "Bad data"});
} else {
db.bookings.save(booking, (err, savedBooking) => {
if (err) {
res.send(err);
}
res.json(savedBooking);
})
}
})
module.exports = router;
using Axios to get data from server
axios.get("http://127.0.0.1:3000/api/bookings/")
.then(res => {
console.log("Get booking info: ", res);
alert(res);
})
.catch(err => console.log(err))
Error:
Network Error
Stack trace:
node_modules\axios\lib\core\createError.js:16:24 in createError
node_modules\axios\lib\adapters\xhr.js:87:25 in handleError
node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
node_modules\react-native\Libraries\Network\XMLHttpRequest.js:578:29 in setReadyState
node_modules\react-native\Libraries\Network\XMLHttpRequest.js:392:25 in __didCompleteResponse
node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:191:12 in emit
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349:47 in __callFunction
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106:26 in <unknown>
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297:10 in __guard
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
...
Please help me.
Thank you very much
Android uses a special type of IP address 10.0.2.2
axios.get("http://10.0.2.2:3000//api/bookings/")
.then(res => {
console.log("Get booking info: ", res);
alert(res);
})
.catch(err => console.log(err))

Resources