`Unexpected behavior when using res.redirect()

Both of these code snippets lead to a redirection to the products/:id path. However, there is a difference in how I need to set up the routes.

In the post route, I must include products/, but in the put route, I do not need to include it.

Does anyone have insight into why this distinction exists? Thank you for your assistance.

router.post("/", async (req, res) => {
    const newProduct = new Product(req.body)
    await newProduct.save()
    console.log(newProduct)
    res.redirect(`products/${newProduct.id}`)
})
router.put("/:id", async (req, res) => {
    const { id } = req.params
    const product = await Product.findByIdAndUpdate(id, req.body,
        {
            runValidators: true,
            new: true
        })
    console.log(req.body)
    res.redirect(`${product._id}`)
}

Answer №1

Redirections take place in relation to the URL of the initial request that caused them.

  • The POST route is activated by POST /products.
  • The PUT route is triggered by PUT /products/123.

Relative evaluation effectively substitutes the last segment of the original URL with the relative URL. This concept can be exemplified using the URL class in Node.js:

> new URL("newid","http://server/products").href
'http://server/newid'
> new URL("products/newid","http://server/products").href
'http://server/products/newid'
> new URL("id","http://server/products/id").href
'http://server/products/id'

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

Guide on utilizing schema methods with mongoose and Express

I keep encountering an issue when trying to execute user.comparePassword from exports.index.post. The issues seems to be isolated to the code provided below, which includes all relevant information. While the UserSchema.pre('save') method works w ...

ReactJS is encountering a situation where two children are using the same key and causing

When I try to view the profile information of another user, I encounter a duplicate key error that says: "Warning: Encountered two children with the same key, ``. Keys should be unique so that components maintain their identity across updates. Non-unique k ...

SASS compilation in Materialize

I am exploring Materialize for the first time and I am new to SASS. To get started, I installed the materialize-sass package by running npm install materialize-sass --save. My next step is to create a color set and compile the CSS file. Could someone guid ...

Efficient version control and change tracking system for Mongoose database operations

I am exploring ways to automatically generate a record (Update) in MongoDB using Mongoose/Node.js/Express whenever changes are made to a document. Being new to Node.js, I am seeking advice on the most effective approach for achieving this. The envisioned ...

The Sequelize hasMany function is functioning properly, however, there seems to be an issue with the inverse relationship not

Currently, I am delving into the world of MySQL relations within Node Js using Sequelize with Express Js. When I use User.hasMany(Post);, everything runs smoothly. However, issues arise when attempting to reverse it in the Post model with Post.belongsTo(Us ...

Working with TypeScript to set a value for an object's field

I have two objects of the same model: interface Project { _id?: string title: string description: string goal: string tasks?: Task[] createdAt?: Date updatedAt?: Date } The first object contains all fields from the interface, while the secon ...

Frontend React app encountering communication issue with backend API via proxy connection

Error: Request to /api/v1/products from localhost:3000 could not be proxied to . Refer to https://nodejs.org/api/errors.html#errors_common_system_errors for details (ETIMEDOUT). This issue persists. Frontend -> React Backend -> Express, Node.js ...

Issue: Attempting to send a POST request to the specified API endpoint for creating a product category resulted in a 500 Internal Server Error

My current task involves inserting data into a table using the POST method with an Angular service function. angular.module("productCategoryModule") .factory("productCategoryService",productCategoryService); productCategoryService.$inject = ['$http& ...

Setting the default views directory in express - A guide

I am currently struggling with setting up my routes in express.js properly. Below is a snippet of my code: express.js configuration app.set('views', config.root + '/app/views') app.set('view engine', 'jade') rout ...

Mastering the Art of Displaying Links in Columns within a Table Using ReactJS

I have the following code that fetches data from the backend and displays it in a table. Everything is working correctly. Now, I need to make the first column in the table appear as a link. How can I achieve that? const EditController = () => { c ...

The issue of jQuery POST methods consistently failing

I have set up a Node.js server using Express with a fairly straightforward configuration: var express = require('express'); var app = express(); app.configure(function() { app.use(express.urlencoded()); app.use(express.json()); app ...

Is there a way for me to send a trading view post request to my Node.js application?

My nodeJS application is set up to receive a post request from TV. When the TV sends a POST request with data and application/json headers, my app ends up receiving an empty req.body. I have included app.use(express.json()) Here's an example of the r ...

Tips for preventing CORS issues in a React - GraphQL app

In my current project, I am exploring the capabilities of the Camunda platform. Specifically, I am developing a React application that interacts with a GraphQL API to perform certain actions. After successfully testing the API using Postman, I have identif ...

"Silent Passageway: Connecting Node JS to ASW RDS MySQL Through a Secret

I am currently collaborating on a project with a partner. The backbone of our project is node js, and we are using an AWS RDS MySQL DB for our database. Our main challenge lies in establishing effective communication with the DB through SSH within NodeJS. ...

Navigating to URL with Query String correctly using Express

Below is the code I currently have: app.get('/', function (req, res) { req.query.searchQuery = 'test2' res.redirect('/search'); }); app.get('/search/', function (req, res) { var searchQuery = req.query.search ...

What steps should I take to enable a route guard to authenticate a token once it has been stored in local storage?

I'm currently working on a basic login page with authentication using Angular and Express. Here's what I've got so far: a login component a service that handles http requests and stores the jwt token in local storage a route guard for the ...

Unleashing the Potential of a Single Node Express Server: Hosting Dual Angular Apps with Distinct Path

I have successfully managed to host two separate angular applications (one for customers and one for company staff) on the same node server, under different paths. The setup looks like this: // Serve admin app app.use(express.static(path.resolve(__dirname, ...

The browser is unable to access localhost:3000

Backend: Utilizing an Express server, created with the npx create-express-api command Frontend: Using Next.js, set up with npx create-react-app in the frontend directory Having executed these commands in the root folder, I attempted to run npm start xxx ...

Receive an error stating "Filename is not defined" when attempting to upload an image in React

Postman functioning properly with my backend code. I utilized form-data and added a random file. The file uploaded successfully to the image folder, but a problem arises when it comes to React. It fails to upload and displays an error on the backend stati ...

Pass the JavaScript variable and redirect swiftly

One of the functionalities I am working on for my website involves allowing users to submit a single piece of information, such as their name. Once they input their name, it is sent to the server via a post request, and in return, a unique URL is generated ...