node.js express handling other .get tries - javascript

Currently I am using
app.get('/prices/all', function (req, res) {
fs.readFile( __dirname + "/" + "data.json", 'utf8', function (err, data) {
res.set({ 'content-type': 'application/json; charset=utf-8' })
res.end( data );
});
})
which all works great however I want to send an error json response if a user attempts to use any other url e.g. /prices on its own. e.g.:
{status:"failed", error:"wrong get attempt"}
this is hosted on a sub-domain so all links for api.sitename.com/# need to be removed but /prices/all

Express JS allows you to define custom error handling for unmapped routes. As such, you could create a function which would respond with the JSON you specified, when the requested resource is not present 404.
app.use(function(req, res) {
res.send('{"status":"failed", "error":"wrong get attempt"}', 404);
});
http://expressjs.com/en/guide/error-handling.html
For further reading as to why this is the preferred way to handle 404 responses, see below:
http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html

Add this as your last route
app.use(function(req, res, next) {
res.status(404).json({status:"failed", error:"wrong get attempt"});
});
Your routes file should look like
app.get('/prices/all', function (req, res) {
fs.readFile( __dirname + "/" + "data.json", 'utf8', function (err, data) {
res.set({ 'content-type': 'application/json; charset=utf-8' })
res.end( data );
});
})
app.use(function(req, res, next) {
res.status(404).json({status:"failed", error:"wrong get attempt"});
});

Related

Connection refused error post request at javascript file on node.js server

I'm getting net::ERR_CONNECTION_REFUSED error when i open related page with javascript file.
I'm using node.js as a server and , i'm writing post requests in a javascript file for my static pages. service_provider.js is my javascript file for i use writing javascript functions for my static pages(html). node.js is my node.js server file.
service_provider.js
function getJourneyAnalize(
_fonkSuccess,
_fonkBefore,
_fonkError,
_deviceId,
_driverId,
_dateStart,
_dateEnd,
_timeStart,
_timeEnd,
_map,
_kmStart,
_kmEnd
) {
var _fromBody = {
device_id: _deviceId,
driver_id: _driverId,
date_start: _dateStart,
date_end: _dateEnd,
time_start: _timeStart,
time_end: _timeEnd,
map: _map,
km_start: _kmStart,
km_end: _kmEnd
};
$.ajax({
type: 'POST',
url: apiUrl + '/ReportFms/JourneyAnalize',
data: JSON.stringify(_fromBody),
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf-8',
beforeSend: function (xhr, settings) {
_fonkBefore();
xhr.setRequestHeader('Authorization', 'Bearer ' + currentUser.access_token);
},
success: _fonkSuccess,
error: _fonkError
});
}
node.js
const express = require('express');
const app = express();
var path = require('path');
app.use(
function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
}
)
app.use('/node_modules/jquery/dist', express.static(path.join(__dirname, '../node_modules/jquery/dist')))
app.get('/static-pages/journey-analize-report', function (req, res) {
res.sendFile(path.join(__dirname + '/../static-pages/journey-analize-report/index.html'))
})
app.listen(8000, () => {
console.log('server started');
})
Does you static page shows correctly ?
1 - If your static page is in the parent folder, get rid of the first slash
res.sendFile(path.join(__dirname + '../static-pages/journey-analize-report/index.html'))
2 - to serve jquery script in your static file you could define a personnalized path in place of node_module folder
Replace:
app.use('/node_modules/jquery/dist', express.static(path.join(__dirname, '../node_modules/jquery/dist')))
With
app.use('/js', express.static(path.join(__dirname, '../node_modules/jquery/dist')))
and in your html file require jquery with personnalized path
<script src="/js/jquery.min.js"></script>
3 - if the error still exist, comment app.use functions and jquery script in static page. Reload the server to see if its work

Posting form data using request module - Nodejs & Express

I'm using a platform for data security, and they have this code snippet showing how to post data to their platform:
They're using the request module: https://github.com/mikeal/request
const request = require('request');
request({
url: 'https://mypass.testproxy.com/post',
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({'secret' : 'secret_value'})
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log('Status:', response.statusCode);
console.log(JSON.parse(body));
}
});
It works fine, but I wanted to replace the 'secret' : 'secret_value' object with my form data, but I'm having a hard time figuring out how to do this.
The only way I know how to retrieve form data is with req.body:
function(req, res) {
var form = {
card_number: req.body.card_number,
card_cvv: req.body.cvv,
card_expirationDate: req.body.card_expirationDate,
};
// ...
});
How would I do that? Any help is greatly appreciated.
I know the code below is wrong, but that's the idea of what I want to achieve:
request( function(req, res) {
var form = {
card_number: req.body.card_number,
card_cvv: req.body.cvv,
card_expirationDate: req.body.card_expirationDate,
};{
url: 'https://mypass.testproxy.com/post',
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(form)
...```
The form data will be sent with the content type application/x-www-form-urlencoded e.g. card_number=123&cvv=456.
Express has a middleware to parse that https://expressjs.com/en/api.html#express.urlencoded
app.use(express.urlencoded());
The parsed values will be in req.body in your post route. So e.g. req.body.card_number will contain the value 123.
You can put the request inside the route:
app.post('/', function (req, res) {
var form = { /* ... */ }
request({
body: JSON.stringify(form),
/* ... */
})
})

Proxy request with Node.js: net::ERR_EMPTY_RESPONSE

Ultimately I am just trying to POST an image from the browser to a server. Unfortunately running into CORS issues, so for the moment, attempting to use our Node.js server as a proxy server.
I have this:
router.post('/image', function (req, res, next) {
const filename = uuid.v4();
const proxy = http.request({
method: 'PUT',
hostname: 'engci-maven.nabisco.com',
path: `/artifactory/cdt-repo/folder/${filename}`,
headers: {
'Authorization': 'Basic ' + Buffer.from('foo:bar').toString('base64'),
}
});
req.pipe(proxy).pipe(res).once('error', next);
});
the browser initiates the request, but I get an error in the browser saying I get an empty response, the error is:
Does anyone know why this error might occur? Is there something wrong with my proxy code in Node.js? Authorization should be fine, and the requeset url should be fine. Not sure what's going on.
Ok so this worked, but I am not really sure why:
router.post('/image', function (req, res, next) {
const filename = uuid.v4();
const proxy = http.request({
method: 'PUT',
hostname: 'engci-maven.nabisco.com',
path: `/artifactory/cdt-repo/folder/${filename}`,
headers: {
'Authorization': 'Basic ' + Buffer.from('foo:bar').toString('base64'),
}
}, function(resp){
resp.pipe(res).once('error', next);
});
req.pipe(proxy).once('error', next);
});
There is an explanation for why this works on this Node.js help thread:
https://github.com/nodejs/help/issues/760

Alternative way of sending array to NodeJS using AJAX

So I've had a lot of problems with sending arrays to NodeJS using AJAX, when sending it with JSON, the error function always gets called (asking why that is has given me no answer that I could use).
So I was wondering if anyone knows a different approach to this, the one that I have right now is:
$.ajax({
type: 'POST',
url: 'http://localhost:1337/deposit?steamid=' + steamid,
contentType: "application/json; charset=UTF-8",
dataType: 'json',
data: JSON.stringify({arr:items}),
success: function(data) {
console.log("Tradeoffer has been sent");
},
error: function(data) {
alert("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
console.log("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
}
});
And on the server side:
app.post('/deposit', function(req, res) {
console.log('Deposit request recieved, info:');
console.log('STEAM ID: ' + req.query.steamid);
console.log('ITEMS: ' + req.body.arr);
});
So I was wondering if someone could tell me another way of sending an array.
If you can tell me what's wrong with this code, that would be awesome to of course.
app.js
//nodejs v4.2.6
var express = require('express');
var app = express();
var fs = require('fs');
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.get('/test', function(req, res) {
fs.readFile('test.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.post('/deposit', function(req, res) {
console.log('Deposit request recieved, info:');
console.log('STEAM ID: ' + req.query.steamid);
//console.log('ITEMS: ' + req.body.arr);
res.send({'finish':'finish'});
});
app.listen(3000, function(){
console.log('http Express server(worker) listening on port 3000');
});
test.html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
</head>
<body>
<script>
var steamid = 1;
$.ajax({
type: 'POST',
url: 'http://localhost:3000/deposit?steamid=' + steamid,
contentType: "application/json; charset=UTF-8",
dataType: 'json',
data: JSON.stringify({arr:[1,2,3,4]}),
success: function(data) {
console.log("Tradeoffer has been sent");
},
error: function(data) {
alert("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
console.log("Failed to call bot, please inform us about this issue by DM'ing us at https://twitter.com/csgobeararms");
}
});
</script>
</body>
</html>
I think that you listen to the wrong URL in Node. From AJAX you call url: http://localhost:1337/deposit?steamid=' + steamid,, but you listen to '/deposit' in Node.
You could try using RegExp:
app.post(new RegExp('/deposit?steamid=[a-zA-Z0-9]')
(assuming that `steamid only contains alphanumerical characters).
Since you're not sending a GET request you might as well get rid of the steamid parameter in the URL and call http://localhost:1337/deposit/' + steamid,; you should then listen to app.post(new RegExp('/deposit?steamid=[a-zA-Z0-9]') in Node.
Hope this helps!

Cannot GET / DELETE Express.js

I have this script with which I'm trying to POST, GET and DELETE some stuff.
When I try POST or GET, the right messages are logged, but when I try DELETE, I get the following error:
Cannot GET /del_user
The URL I'm using is http://127.0.0.1:8081/del_user
What can be wrong in here?
var express = require('express');
var app = express();
// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I solved it by changing the app.delete to app.get and then placing the required remove statement inside the app.get. Something like this :-
app.get('/delete/:userId', (req, res) => {
Users.remove({ _id: req.params.userId }, (error, posts) => {
if (error) {
console.warn(error);
}
else {
data = posts
res.render("delete", {"data": data})
}
});
});
In your code you're binding the /del_user URL to the HTTP DELETE method.
So all you need to do is specify the DELETE method in your application or in Postman.
If you're not using it, it's an App in Google Chrome and you might want to download it, it makes your life a LOT easier ;)
Also, since the HTTP method is already declared to be DELETE, there is no need to specify it in the URL.
This is part of the RESTful working.
If you are using AJAX to try your code, you need to specify the method, which is delete.
$.ajax({
url: "http://127.0.0.1:8081/del_user",
type: "DELETE"
});

Categories