Express middleware with different methods (PUT/POST) on a route - javascript

app.route('/ad/apply')
.put(adController.applyAd)
.post(notificationController.addNotification)
Above route won't work, I got error 404 not found if I added in 3rd line like that. How do I do PUT and then POST? if it's both PUT I can just do
app.route('/ad/apply')
.put(adController.applyAd, notificationController.addNotification)

Above route won't work, I got error 404 not found if I added in 3rd line like that.
To reproduce your scenario locally, I tried the following code. It didnt have any specific issues with line alignment.
'use strict';
let http = require('http');
let express = require('express');
let app = express();
let server = http.createServer(app);
const PORT = 8888;
server.listen(PORT, () => {
console.log(`Server is up at ${PORT}`);
app.route('/').put((req, res) => {
return res.status(200).send({
msg: 'hello from PUT'
});
}).post((req, res) => {
return res.status(200).send({
msg: 'hello from POST'
});
});
});
May be, 404 is because of some other routes taking precedence over this based on the order of declaration.

Related

I cannot get my JavaScript REST API to return data

I know there are many similar questions about this issue and most of them are already answered, but I am a beginner on this.
This code is a code from a YouTube tutorial about the basic of making REST API, as follows:
const app = require('express')();
const PORT = 8095;
app.get('/tshirt', (req, res) => {
res.status(200).send({
tshirt: "red white tshirt",
size: "large"
})
});
I tried to access get tshirt both from browser and Insomnia and it says 'could not get /tshirt', what might be wrong?
You also need to start the actual server.
const express = require('express');
const app = express();
const port = 8095;
app.get('/tshirt', (req, res) => {
res.status(200).send({
tshirt: "red white tshirt",
size: "large"
})
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
As per https://expressjs.com/en/starter/hello-world.html

Unable to verify leaf signature npm

const express = require('express');
const https = require('https');
const app = express();
app.get("/" , function(req, res) {
const url = "https://api.openweathermap.org/data/2.5/weather?q=Bhubaneswar&appid=5b1ee8df0720f3eca886c9ca1cb03385&units=metric";
https.get(url, function(request, response){
console.log(response);
});
res.send("Server is up & running");
});
app.listen(5000, function() {
console.log("Server is running at port 5000");
});
[Nodemon app getting crashed][1]
[1]: https://i.stack.imgur.com/rka1M.jpg
When ever am running the nodemon, error is arising as UNABLE_TO_VERIFY_LEAF_SIGNATURE. Even tried several ways provided bu Stack Overflow & GitHub. Still none of them worked out.

Express.js Handle unmached routes

Fellows I develop a Rest API and I want when a route does not exist to send a custom message instead of an html one that express.js sends by default. As fas as I searched I could not find a way to do that.
I tried to do:
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
But it matches and all already implemented methods. I want only the unmached one to get handled by my app.
Edit 1
For each enndpoint I create a seperate file having the following content: eg. myendpoint.js
module.exports=function(express){
var endpoint="/endpoint"
express.get(endpoint,function(req,res){
res.end("Getting data other message")
}).post(endpoint.function(req,res){
res.end("Getting data other message")
}).all(endpoint,function(req,res){
res.status(501)
res.end("You cannot "+res.method+" to "+endpoint)
})
}
An in my main file I use:
var endpoint=require('myendpoint.js')
var MyEndpointController=endpoint(app)
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
1.Declare all of your routes
2.Define unmatched route request to error respose AT the END.
This you have to set it in the app. (app.use) not in the routes.
Server.js
//Import require modules
var express = require('express');
var bodyParser = require('body-parser');
// define our app using express
var app = express();
// this will help us to read POST data.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8081;
// instance of express Router
var router = express.Router();
// default route to make sure , it works.
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// test route to make sure , it works.
router.get('/test', function(req, res) {
res.json({ message: 'Testing!' });
});
// all our routes will be prefixed with /api
app.use('/api', router);
// this is default in case of unmatched routes
app.use(function(req, res) {
// Invalid request
res.json({
error: {
'name':'Error',
'status':404,
'message':'Invalid Request',
'statusCode':404,
'stack':'http://localhost:8081/'
},
message: 'Testing!'
});
});
// state the server
app.listen(port);
console.log('Server listening on port ' + port);
Please note : I have prefix '/api' in my routes.
Please try http://localhost:8081/api
You will see '{"message":"hooray! welcome to our api!"}'
When you try http://localhost:8081/api4545 - which is not a valid route
You would see the error message.
First you need to define all existing routes then at last you have to define no
route. order is very important
// Defining main template navigations(sample routes)
app.use('/',express.static(__dirname + "/views/index.html"));
app.use('/app',express.static(__dirname + "/views/app.html"));
app.use('/api',express.static(__dirname + "/views/api.html"));
app.use('/uploads',express.static(path.join(__dirname, 'static/uploads')));
//If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
res.status(404);
res.json({status:404,title:"Not Found",msg:"Route not found"});
next();
});
Can't post as comment (reputation is too low ...) but did you define this route after all your other paths ?
The order is really important, you should first define all your routes and then have this one.
on my case for the safetyness of my routes life cycle I used this **/** or */*, *(asterisk) operator stands for all, and here's my example.
app.use('**/**',express.static(path.join(__dirname, './public/not-found/index.html')));

Node.js simple app doesn't get second get request

I try to run very basic script as following:
import express from "express";
const PORT = 3000;
const app = express();
app.set("json spaces", 4);
app.get("/", (req, res) => res.json({status: "NTask API"}));
app.get("/tasks", (req, res) => {
res.json({
tasks: [
{title: "Buy some shoes"},
{title: "Fix notebook"}
]
});
});
app.listen(PORT, () => console.log(`NTask API - Port ${PORT}`));
the results are:
{
"status": "NTask API" }
My question is, why the tasks is not there?
Thanks
Making my comment into an answer since it turned out to be the solution.
You are getting the results for a request to /. If you want the tasks, you have to request /tasks.

Ignore header validation for HTTP requests in Node

I am building a proxy server which is supposed to forward data from an Shoutcast server to the client. Using request or even Node's http module this fails due to missing HTTP header:
{ [Error: Parse Error] bytesParsed: 0, code: 'HPE_INVALID_CONSTANT' }
The URL in question is: http://stream6.jungletrain.net:8000
Doing a header request with curl I was able to verify this:
$ curl -I http://stream6.jungletrain.net:8000
curl: (52) Empty reply from server
Yet the stream is working fine as tested with curl stream6.jungletrain.net:8000.
Is there a way to disable the header verification in request or Node's http? This is the code I am testing it on:
var express = require('express');
var request = require('request');
var app = express();
app.get('/', function (req, res) {
request('http://stream6.jungletrain.net:8000').pipe(res);
stream.pipe(res);
});
var server = app.listen(3000, function () {
console.log('Server started')
});
I am aware this can be achieved by rolling an implementation with net, there is also icecast-stack but subjectively seen it only implements half of the Stream interfaces properly.
Using icecast, I was able to get this working both using the on('data') event and by piping it to the Express response:
var express = require('express');
var app = express();
var icecast = require('icecast');
var url = 'http://stream6.jungletrain.net:8000';
app.get('/', function(req, res) {
icecast.get(url, function(icecastRes) {
console.error(icecastRes.headers);
icecastRes.on('metadata', function(metadata) {
var parsed = icecast.parse(metadata);
console.error(parsed);
});
icecastRes.on('data', function(chunk) {
console.log(chunk);
})
});
});
var server = app.listen(3000, function() {
console.log('Server started')
});
Or simply:
app.get('/', function(req, res) {
icecast.get(url).pipe(res);
});
Also of some note:
It appears the icecast package has been superseded by https://www.npmjs.com/package/icy

Categories