The server is unable to process the request with parameters for the specified URL

I've been encountering an error every time I try to post something.

articlesRouter.post('articles/:target', async (req, res) => {
    const target = req.params.target.replaceAll("_", " ")
    const article = await Article.findOne({where: {title: target}})
    if (article)
    {
        const author = req.body.commentAuthor
        const text = req.body.commentText
        await article.createComment({author, text})
        console.log("POST METHOD IS WORKING")
    }
})

Here's the form:

 <form method="post">
            <textarea placeholder="Title of your article" id="title" name="articleTitle"></textarea>
            <br />
            <textarea placeholder="Body of your article" id="body" type="text" name="articleBody"></textarea>
            <br />
            <button id="submit" type="submit">Done</button>
        </form>

Using the GET method:

articlesRouter.get('/articles/:target', async (req, res) => {
    const target = req.params.target.replaceAll("_", " ")
    const searchResult = await Article.findOne({where: {title: target}})
    if (searchResult)
    {
        const correspondingComments = await searchResult.getComments()
        res.render('../views/currentArticle', {title: searchResult.title, text: searchResult.body, comments: correspondingComments})
    }
    else{
        console.log('Error')
    }
})

As you can see, the path to the article includes /articles and /title_of_article. I suspect the issue may lie with this line

articlesRouter.post('articles/:target'.....

Could it be that I can't use the post method with /:params??? Thanks for taking the time to read!

Answer №1

  • When submitting a form via POST, the input will be found in req.body rather than req.params.
  • It is recommended to exclude the param :target from the route path and ensure there is a '/' before 'articles' for a complete route path.
  • To complete the request, send a response such as res.status(200).end() or res.send('ok').

Form:

<!DOCTYPE html>
<html>
<head>
  <title>Form</title>
</head>
<body>
  <form method="post" action="/test/articles">
    <textarea placeholder="Title of your article" id="title" name="articleTitle"></textarea>
    <br />
    <textarea placeholder="Body of your article" id="body" type="text" name="articleBody"></textarea>
    <br />
    <button id="submit" type="submit">Done</button>
  </form>
</body>
</html>

app.js:

...
const testRouter = require('./routes/test');
...
app.use('/test', testRouter);
...

test.js:

const express = require('express');
const articlesRouter = express.Router();

articlesRouter.post('/articles', (req, res) => {
  const target = req.body.articleTitle.replaceAll("_", " ")
  console.debug(target)
  // ... your DB access code
  res.send('ok')
})

module.exports = articlesRouter;

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

Tips for cutting down on bundle size in your WEBPACK setup when using VUEJS

I have tried numerous tutorials to reduce the size of my bundle, but none of them seem to be affecting the bundle size and I can't figure out why. Every time I integrate new code into webpack, the bundle size remains unchanged. (The application is c ...

Inconsistencies observed during the native JSON import process in JavaScript

Encountered a strange behavior when loading a JSON file into JavaScript while working on a React project. Seeking an explanation and guidance on properly accessing data from the JSON data store. The JSON file contains product data: { "product ...

"Converting a text into a property that can be

In my scenario, I have a set of fixed options along with a dynamic number of yes/no radio inputs named other[index]. By utilizing $(form).serializeArray(), I can obtain an array of name/value objects. Through the use of the reduce method, I am then able to ...

Utilizing and interpreting the input data provided by the user in jQuery

While following the tutorial at , I am trying to extract specific parameters from the user input to generate a corresponding URL. Below is the code snippet I am working with: <html> <head> <title>USGS Earthquake Feed</title> ...

Tips for resolving the issue: "Encountered error loading module script..." in Angular 8 and Electron 5

I have been working on developing an Electron 5 app using Angular 8. Despite following numerous online tutorials, I keep encountering the same error. Initially, I set up a new project and ran ng serve --open, which successfully displayed the default angul ...

Encountering errors while attempting to share files in a system built with Node.js, Express,

This snippet shows my Node.js code for connecting to a database using Mongoose const mongoose = require('mongoose'); function connectDB() { // Establishing Database connection mongoose.connect(process see your Naughty's you're sure ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...

Tips for utilizing a received variable within an ejs document

I am currently attempting to update the content of an HTML element in an EJS file with a variable that I have defined in a JavaScript file. let checkbox = document.querySelector('input[name="plan"]'); checkbox.addEventListener('ch ...

Is it possible to utilize both body-parser and Formidable simultaneously?

I've been working on a problem for a few days now, but I'm having trouble understanding certain aspects of it. My website is built using NodeJS and ExpressJS, with form handling done through body-parser. var adName = req.body.adName; var adMess ...

Navigating between pages using the ExpressJS and Angular 1 routing system

Can someone help me troubleshoot an issue I'm having with my Express API and Angular front-end? Whenever I try to access the /about route, it keeps defaulting back to index.html and displaying a 404 error message. Can you take a look at my code and pi ...

Nuxt Page Featuring One Exclusive Product

I am just getting started with Nuxt and I'm in the process of creating a Single Product. I have some questions: How can I generate multiple pages using SSR and create a unique HTML for each page? Should CSR be developed first before implementing SSR, ...

Error encountered when attempting to insert data into database due to incompatible data types

I am experiencing an issue with Vue multiselect. I am trying to save the id of selected options in a database, but it seems that I am encountering an error related to Array to string conversion. I have declared both site_id and administrator in fillables. ...

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

JavaScript can be used to call a web service directly from a content page

Is there a way to call an autocomplete webservice from JavaScript in a content page that is part of the same web app? I have found that when I include a master page, the autocomplete feature stops working. I haven't added a script manager to the maste ...

Ways to retrieve the value of an Object that may have a key that is undefined

Is there a method similar to Angular's $parse service that can be used for accessing nested object properties? Consider an object structure like this: const obj = { items: [ { store: { type: '' } } ] }; Sce ...

Is it possible to create a dedicated page in Next.js using static site generation (SSG)?

The static-site generation (SSG) feature of Nextjs allows for fetching data at build time, resulting in pre-rendered pages using getStaticProps and getStaticPaths. Imagine having a blog with numerous articles that remain static, while some may be updated ...

Running CesiumJS is a straightforward process that can be done by

After diligently following the provided instructions, I managed to get cesium running locally. I then attempted the hello world example as shown: However, despite clicking on "open in browser," I couldn't see anything. It has been a constant struggl ...

When an object is not empty, the function Object.getOwnPropertyNames will still return an empty array

In my code, I am filling $scope.master with data from a csv file. When I populate $scope.master within the function, all the data is present. This can be observed in the log output displayed below. However, outside of the function, although $scope.master ...

Tips on displaying information following the parsing of JSON

Trying to retrieve a list of users using this code snippet <div id="users" data-users='[{"name":"one","userName":"user_one"}, {"name":"two","userName":"user_two&q ...

Can you explain the distinction between Vue's 'v-on' directive and vue.$on method?

If I have two sibling components set up like this: <div id="root2"> <some-component>First</some-component> <some-component>Second</some-component> </div> ... and these components are coded as follows: Vue.comp ...