app.get() function not getting called in node.js - node.js

So I am starting a node.js app, and familiarizing myself with the basics. I have installed express, and am using the get function to create a route and send a response.
However, on entering the webpage on the browser, the page keeps loading and does not give a response. Any idea on what I am doing wrong here? Even the request body does not show up on the logs, so it looks like its not entering the get function.
Below is the code. Any help would be appreciated.
const http = require("http");
const express = require("express");
const bodyparser = require("body-parser");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
console.log(req.body);
res.send("XYZ Homepage");
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});

Related

Express routes working with url params but not with specific sub routes

I'm building an API for my web app and I was able to successfully send requests to the routes in Post.js when they only had url params. But when I try to create a route like '/allposts' (the last endpoint in Post.js) , I receive a 404 error message on postman. Here's my code:
router.post('/', (req, res) => {
// Endpoint 1 code here
})
router.get('/:id', (req, res) => {
// Endpoint 2 code
})
// This is the route that I can't to send requests to
router.get('/ap', async(req, res) => {
try{
const ap = await P.find()
res.send(ap)
} catch(error){
log(error)
res.status(500).send("error")
}
})
server.js
const express = require('express')
var cors = require('cors')
const fs = require('fs');
const path = require('path');
var app = express()
app.use(express.static(path)
app.use(cors())
const bodyParser = require('body-parser')
app.use(bodyParser.json());
var p = require("./routes/P.js");
app.use('/post', p);
const PORT = process.env.PORT || 3001
app.listen(port, () => {
log(`Listening on port ${PORT}...`)
});
When I send a request to http://localhost:3001/post/ap, I'm getting the a 404 Not Found error, but the first two routes work fine. It seems like routes with url params work, but the allposts route does not. Any help would be greatly appreciated. Thanks.
Main problem is the order of the routes.
router.get('/:id') will be initialized before router.get('/allposts'). So when you want to access /allposts the first router will catch it.
You need to switch the init order.
First router.get('/allposts') then router.get('/:id').

Why is my very basic node.js endpoint timing out?

I have a very simple node.js app that looks like this:
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors);
app.use(express.json());
app.get('/', function(req,res) {
return res.json({response: "ok"});
})
app.listen(port, () => {
console.log(`Server is running on ${port}`);
})
When I run nodemon server, I get this response from my terminal:
When I try to hit localhost:3000/, I get this:
And in postman:
I feel like I must have set up something wrong, as I've stripped out all the code and I'm still getting this error. Can anyone please advise?
It should be:
app.use(cors())
You have to invoke the function.

node-fetch use get method for get a specific file content

I use node-fetch for make requests to localhost.
I want to use get method for get specific file content.
An example: my node.js server is a file called app.js, and in the same folder there is a file called config.json, so I want to get (from a discord bot made with discord.js) the content of config.json.
Here my server's code:
const express = require('express');
const app = express();
const fetch = require('node-fetch');
const fs = require('fs')
const port = process.env.port || 1451
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(`my path`, { 'Content-Type': 'text/html' });
});
app.post('/jsonFile', (req, res) => {
console.log(req.body);
})
app.listen(port, () => console.log(`listening on http://localhost:${port}`));
And here is my discord bot code for connecting to my website:
fetch('http://localhost:1451').then(res => console.log(res))
P.S I use express for node.js servers
Maybe you could use fs.readfile to read that config.json file content and then send that content as a response.

Node.js post request returns 404

i'm trying to use postman with "post" method , but when i use it i'm getting a 404 not found error.
i will attach my code and a picture of the error
thanks in advance
using React Native
const express = require('express');
const router = express.Router();
router.post('/signup', (req, res) => {
res.send('You made a post request');
});
module.exports = router;
Picture from Postman app with the error
Things to consider are
1. Make sure you have imported the routes in app.js and used them.
2. Your app is running on 3000 port.
const UserRouter = require('./routes/v1');
app.use('/api',UserRouter);
const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("listening at port",port)
});

node express returns "Cannot Get" other solutions/ code not working. file upload

tldr
Ok i've been trying to get a file upload server working for a few days now and evrything i try just returns cannot get.
i'm currently trying the setup below but it is not working
code
here is server.js
const express = require("express");
const upload = require("./upload");
const cors = require("cors");
var router = express.Router();
var app = express();
const server = express();
var corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
server.use(cors(corsOptions));
router.get("/", function(req, res) {
res.render("index", { title: "Express" });
});
server.post("/upload", upload);
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
Below is upload.js
const IncomingForm = require("formidable").IncomingForm;
module.exports = function upload(req, res) { var form = new IncomingForm();
form.on("file", (field, file) => {
// Do something with the file
// e.g. save it to the database
// you can access it using file.path
console.log("thisno werk"); }); form.on("end", () => {
res.json(); }); form.parse(req); };
Let's mean server as the result of the const server = require('express')();, and router as the result of const router = require('express').Router();.
server is an instance of your Express server while router is an instance of API endpoints router. You don't only need to write your router router.get();, but you also need to set the appropriate files (so-called controllers) for handling API requests.
So your code should have this line: server.use('/', yourController); or simply server.get('/', handlingFunction); if you don't have API sections.
However, if you use routers, then you need the first variant.
Your POST /upload method works great because it's configured on the app level. But you need to fix your GET / method because it's configured on the router level that is unused in your app.
Source: Express routing

Resources