Question:
Hopefully my code is formatted correctly, this is my first time posting.
I am having a problem with accessing the response object methods inside the callback used within app.post().
When I run a post request, I can get the data fine but I can’t use res.json(), res.send(), res.sendFile() or any of the like.
It returns Cannot Get /api/shorturl/new
When you change it to a get request there is no issue and you can use all of the response methods.
I am aware with express 5 they have changed how the response methods are used a bit. I have tried res.status(res.statusCode).json({message:“hello”}) but nothing works you just keep getting:
Cannot GET /api/shorturl/new
When you add error handling to the js code below you get this:
express deprecated res.send(status, body): Use res.status(status).send(body) instead index.js:44:43
Even with the above error occurring the end result is still:
Cannot GET /api/shorturl/new
The error above is how I figured out that express had changed to some degree but like I said, I tried that too but to no avail.
The express version is: 4.18.2
This is all for a freeCodeCamp.org test:
URL Shortener Microservice on the backend tests
Repl link:
index.js - boilerplate-project-urlshortener - Replit
<!DOCTYPE html>
<html>
<head>
<title>URL Shortener Microservice | freeCodeCamp.org</title>
<link
rel="icon"
type="image/png"
href="https://cdn.freecodecamp.org/universal/favicons/favicon-16x16.png"
/>
<link href="/public/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>URL Shortener Microservice</h1>
<main>
<section>
<form action="/api/shorturl/new" method="post">
<fieldset>
<legend>URL Shortener</legend>
<label for="url_input">URL:</label>
<input id="url_input" type="text" name="url" placeholder="https://www.freecodecamp.org/" />
<input type="submit" value="POST URL" />
</fieldset>
</form>
</section>
<script>
</script>
</main>
<footer>
<p>By <a href="https://www.freecodecamp.org/">freeCodeCamp</a></p>
</footer>
</body>
</html>
require('dotenv').config();
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require("body-parser");
app.use(cors());
app.use(bodyParser.urlencoded({extended:true}));
app.use('/public', express.static(`${process.cwd()}/public`));
app.post("/api/shorturl/new", (req,res)=>{
res.json({
message:"HELLO"
})
})
app.get('/', (req, res,)=>{
res.sendFile(process.cwd() + '/views/index.html');
});
const port = process.env["PORT"] || 3000;
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});