Node Express how to edit the app.post url - node.js

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 '/'

Related

Returning data to a user from an external API

i am trying to return the value of my search after using the node-spotify-api package to search for an artist.when i console.log the spotify.search ..... without the function search function wrapped around it i get the values on my terminal..what i want is when a user sends a request to the userrouter routes i want is to display the result to the user..i using postman for testing ..
This is the controller
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.ID,
secret: process.env.SECRET,
});
const search = async (req, res) => {
const { name } = req.body;
spotify.search({ type: 'artist', query: name }).then((response) => {
res.status(200).send(response.artists);
}).catch((err) => {
res.status(400).send(err);
});
};
module.exports = {
search,
};
**This is the route**
const express = require('express');
const searchrouter = express.Router();
const { search } = require('./spotify');
searchrouter.route('/').get(search);
module.exports = searchrouter;
**This is my server.js file**
const express = require('express');
require('express-async-errors');
const app = express();
require('dotenv').config();
// built-in path module
const path = require('path');
// port to be used
const PORT = process.env.PORT || 5000;
// setup public to serve staticfiles
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('port', PORT);
const searchrouter = require('./route');
app.use('/search', searchrouter);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(PORT, (req, res) => {
console.log(`Server is listening on port ${PORT}`);
});
[that is my project structure][1]
Well Your Code has a bug
Which is
searchrouter.route('/').get(search);
You are using a get request and still looking for a req.body
const { name } = req.body;
name is going to equal to = undefined
and when this runs
spotify.search({ type: 'artist', query: name })
it's going to return an empty object or an error
req.body is empty for a form GET request
So Your fix is
change your get request to a post
searchrouter.route('/').post(search);

When I run the server, it gives me a message "Cannot GET /". What am I doing wrong?

I am trying to do a GET request in order to retrieve some images from my Cloudinary account. But when I run the server, I get a 400 status code on my UI with reading
Cannot GET /
How can I solve this issue?
const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const { json } = require('body-parser');
const axios = require('axios');
const app = express();
app.use(cors());
app.use(json());
const { parsed: config } = dotenv.config();
const BASE_URL = `https://api.cloudinary.com/v1_1/${config.CLOUD_NAME}/resources/image`;
const auth = {
username: config.API_KEY,
password: config.API_SECRET,
};
app.get('/photos', async(req, res) => {
const response = await axios.get(BASE_URL + '/resources/image', {
auth,
params: {
next_cursor: req.query.next_cursor,
},
});
return res.send(response.data);
});
app.get('/search', async (req, res) => {
const response = await axios.get(BASE_URL + '/resources/search', {
auth,
params: {
expression: req.query.expression,
},
});
return res.send(response.data);
});
const PORT = 7000;
app.listen(PORT, console.log(`Server running on port ${PORT}`));
If you open your server URL in browser you will get Cannot GET / because you don't have base route.
It's not needed in most cases, since you don't access your node server from browser, it just run's in the background.
You generally display your frontend (Angular, React) in browser.
But if you don't like the message you can add a base route.
app.get('/', (req, res) => res.send('Hello World'));
I'm not sure what are you trying to achieve, but at least you won't get this error.

How to fix/troubleshoot React Express 404 Error with static site?

I have an input that calls this submit function onSubmit:
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setfruit(item);
console.log("sent")
fetch('/api/tasks/add', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ Name: item.Name,Quantity: item.Quantity, edit: item.edit }),
}).then(() => {
setItem(itemd)
getTasks();
});
};
and my route:
router.post('/add', (req, res) => {
const { Name, Price, edit } = req.body;
const newTask = new Task({ Name, Price, edit });
newTask.save()
.then(task => res.json(task))
.catch(err => res.json(500, err));
});
Heres my index.js:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const routeTasks = require('./src/routes/tasks');
app.use(express.static(path.join(__dirname, './client/build')));
app.use(bodyParser.json());
app.use('/api/tasks', routeTasks, (req, res) => res.sendStatus(401));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + './client/build/index.html'));
});
const port = 5000;
app.listen(port);
console.log(`listening on ${port}`);
Every time I call the onSubmit function, I get a 404 error. I can't tell why.
I used this repo as a guide for creating my express server but for some reason when I switch the underlying React app it stops working.
https://github.com/jmsv/simple-mern
Per Phil's comment, my issue was that the example Repo I was going off of used a React proxy which I hadn't configured in my own app. Once I added that to the package.json file, it worked.

How to Make API calls in express server

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

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