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

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.

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

error when get html file by express js and javascript

I a beginner with Express js and when I reload the server to show the HTML file display "Cannot get" this is photo from the console and its show som errors
this my code server-side:
and this is a photo from git bash and the server is working
and this is my HTML code
help, please
Instead of app.route(), use app.get()
like this
const express = require("express)
const path = require("path")
const app= express()
app.get("/",(req,res)=>{
res.sendFile(path.join(__dirname, './index.html'))
})
app.listen(3000,()=>{
console.log("server running at port 3000")
})
app.route takes a string as an argument and returns a single route - you're passing a callback function, so change your route handling to the following:
// use the appropriate HTTP verb
// since you're trying to serve the `index.html` file,
// `get` should be used
app.route("/")
.get((req, res) => {
res.sendFile(path.join(__dirname, './index.html')
})
Alternatively, you could just do the following:
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, './index.html')
})
Here's a working example:
// thecodingtrain/
// index.js
// home.html
// package.json
const path = require("path")
const express = express()
const app = express()
const PORT = 3000
app.route("/")
.get((req, res, next) => {
res.sendFile(
path.join(__dirname, "./home.html")
)
})
app.listen(PORT, () => {
console.log(`Listening on port ${PORT})
})
Hope this helps.

Trying to follow a sample and I can't figure out why there are errors

Trying to follow a sample and I can't figure out why there are errors. Any help...it's probably a formatting thing:
import http from 'http';
import express from 'express';
// Express app setup
const app = express();
const server = http.createServer(app);
server.listen(3000);
server.on('listening', () => {
console.log('Server is listening on port: 3000');
app.get('*', (req, res) => {
res.end('Hello Express');
});};
My two error messages are:
Parsing error: Unexpected token, expected ","
9 | app.get('*', (req, res) => {
10 | res.end('Hello Express');
11 | });};
| ^
')' expected.
There’s a few issues here:
The import syntax is not valid in nodejs unless you have a transpiler to intercept it.
Your setup with express is just wrong. You’re defining your route handlers after you’ve started the server.
Here’s what you want - with valid common js syntax
const http = require('http')
const app = require('express')()
app.get('*', (req, res) => res.send(' Hello Express'))
const server = http.createServer(app)
server.listen(3000, () => console.log('Server is listening on port: 3000'))

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

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.

Facebook Bot and Node: Empty req.query

this is my first post on StackOverflow!
I have a problem with a new bot I'm creating.
First of all, this is my code in app.js
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from "mongoose";
import { VERIFY_TOKEN, PORT, MONGODB_URI } from './config';
import { botLogic } from './logic';
mongoose.Promise = global.Promise;
mongoose.connect(MONGODB_URI, { useMongoClient: true });
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Correcly deployed!');
});
app.get('/webhook', (req, res) => {
if(req.query['hub.verify_token'] === VERIFY_TOKEN) {
res.send(req.query['hub.challenge']);
}
res.send('Invalid credentials');
});
app.post('/webhook/', async (req, res) => {
try {
await res.sendStatus(200);
await Promise.all(req.body.entry.map(async entry => {
await Promise.all(entry.messaging.map(async update => {
console.log(`Received update from ${update.sender.id}`);
await botLogic(update);
}));
}));
} catch (e) {
console.error(e);
}
});
app.get('*', (req, res) => {
res.status('404').send('Nothing interesting here');
});
app.listen(PORT, function() {
console.log('running on port', PORT);
});
I created the app on the Facebook Developer page and the webhook is linked:
Facebook developer page: webhook
If you go on https://my-personal-bot.herokuapp.com/ it should say
correctly deployed
but If you go here
https://my-personal-bot.herokuapp.com/webhook
is gonna say:
Invalid credentials
and if I log req.query the result is an empty object.
Logs screenshot
I built a couple of bots before and this initial setup was quite straightforward, however, I this particular case, I can't figure out where is the problem. The API version that I'm using is v2.11, it's the only difference with my previous bots.
Thank you in advance for any advice!
the body of the webhooks from Facebook is only json encoded, so get rid of the line that adds url encoding:
app.use(bodyParser.urlencoded({extended: false}));
Also the request is encrypted using your app secret, so you'd need to decode that before using bodyParser.json()
app.use(xhub({algorithm: 'sha1', secret: process.env.APP_SECRET }));
of course you wanna set your env variable APP_SECRET in the heroku console
For a complete example usage of webhooks, look at https://github.com/mduppes/webhooks_test/blob/master/index.js

Categories