Tips for bypassing an argument using the POST method in NodeJS

Hey there! I started off by creating a question about passing over data using the GET method, but now I'm facing a new problem when trying to pass over data with the POST method. Below is my code snippet where things seem to be going wrong. My goal is to display: "Hello (Whatever the user passes as their name)!" If ExpressJS isn't working, can someone guide me on how to achieve this in JavaScript?

Check out the code below:

var server = require('./server');
var router = require('./router');
var requestHandlers = require('./requestHandlers');
 
var handle = {
  '/': requestHandlers.start,
  '/start': requestHandlers.start,
  '/upload': requestHandlers.upload,
  '/show': requestHandlers.show
};

var express = require('express')
var app = express()

app.post('/view/users/:name', function(req, res) {
    console.log(req.body.desc);
    res.end();
});

app.listen(8080, function () {
  console.log('listening on port 8000!')
}) 

When I try to pass over data, I encounter the error message "Cannot GET /view/users/John"

Answer №1

To retrieve the value stored in the path variable :name, you can access it from the req.params object.

app.get('/view/users/:name', function(req, res) {
    console.log(req.params.name);
    res.end();
});

Answer №2

It is essential to include the bodyParser module before defining your routes:

var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

By doing this, any data you send through the route will be easily accessible within the request object thanks to bodyParser.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoking a module function within a callback function in Node.js

I created a module that logs data to a file using Coffeescript. Here's an example: require = patchRequire(global.require) fs = require('fs') exports.h = log: ()-> for s in arguments fs.appendFile "log.txt", "#{s}\n", ( ...

discovering a new type of mutation through the use of Vuex

Vue Component computed: { score () { this.$store.commit('fetchCoordinates'); console.log(this.$store.getters.cordinate); } } store.js export default { state: { lat:'ok', }, getters:{ cordinate(state){ r ...

When you run 'npm install', it triggers a 'npm ERR! code E401' message to appear

My co-worker is having trouble running 'npm install' even though I can do it successfully on my machine. Her command starts fine and seems to be running well for a few minutes, but then it stops abruptly with this error: npm ERR! code E401 npm ...

Creating captivating visuals using the perfect aspect ratio formula

I've been exploring the world of graphic magic in node.js Check out my code snippet below: gm('images/imagename').resize(200, 109, '^>').write('images/newimagename', function (err) { }); It's functioning as ex ...

Eliminating the impact of a CSS selector

I have a complex mark-up structure with multiple CSS classes associated: classA, classB, classC, classD. These classes are used for both styling via CSS and event binding using jQuery selectors. The Challenge: I need the jQuery events to be functional whi ...

Steps to isolate the "changed" values from two JSON objects

Here is a unique question that involves comparing JSON structures and extracting the differences. A JqTree has been created, where when the user changes its tree structure, both the "old" JSON and "new" JSON structures need to be compared. Only the values ...

Is it possible to switch the linter in grunt.js to jslint instead?

Is it feasible to switch the linter used by grunt.js from jshint to jslint, considering that I am more accustomed to using jslint over jshint as the default linter? ...

Tips for adjusting a web address provided by a user

I have a JavaScript code that prompts the user to input a URL and then appends it to a div. The code is working fine, but now I am trying to add functionality to edit the entered URL by changing the width and height of any iframes before appending them. ...

Is it possible to retract a message on Discord after it has been sent?

I have a code that automatically sends a welcome message when a new member joins the guild, and I want it to be deleted shortly afterwards. Here is my current code: client.on('guildMemberAdd', (member) => { var server = member.guild.id; i ...

When attempting to set the keyPath using a variable, an error occurs stating that the keyPath option is not a valid key path

My JSON object, stored in a variable named "jsonObjSuper", is structured like this: { "Watchlist": "My Watchlist", "Instruments": { "instrument1": [ "Company ABC", [ { "snapshotTimeUTC": "2018-11-01T00:00:00", "snapshotTime": "2018/11/ ...

Tips for effectively handling errors in NodeJS

As I venture into the world of NodeJS and Express, I find myself faced with the challenge of asynchronously calling DB functions. This is quite different from my experience with other popular scripting languages and a C++ background. Despite figuring out a ...

What could be the reason for the onmessage listener not handling the initial SSE event?

When a client connects to a Node Express server, it creates a new EventSource. The server sends an SSE event upon initial connection and then at a 30-second interval thereafter. Strangely, the client's onmessage handler does not respond to the initial ...

Creating Multiple Requests in Express/Mongoose: A Step-by-Step Guide for Embedding Models

As a newcomer to Express, I have been experimenting with Mongoose. Here's the issue I am facing - I want to create a post request where new friends can be added but only to one user. Each user should be able to have up to ten friends. User Schema - c ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

An error occurred in the defer callback: The specified template "wiki" does not exist

I recently developed a Meteor package called Wiki. Within the package, I included a wiki.html file that contains: <template name="wiki"> FULL WIKI UI CODE HERE </template> Next, I created a wiki.js file where I defined my collections and eve ...

Unknown provider in Angular when using factory inside anonymous function wrapper

I encountered an issue with an unknown provider error when using a factory and declaring it with an anonymous function: (function () { 'use strict'; angular.module('app').factory('errorCodeFactory', errorCodeFactory) ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

"Mastering the Art of Placing the VuetifyJS Popover: A Comprehensive

When using VueJS with VuetifyJS material design components, how can I adjust the positioning of the Vuetify popover component to appear below the MORE button? The current placement is in the upper left corner which I believe defaults to x=0, y=0. Button: ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually? I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this ...