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

Exporting two functions in JavaScript

Currently utilizing React, Redux, and experimenting with Material-UI integration. The example codes provided by Redux and Material-UI libraries include an 'export' statement at the end. Redux: export default connect(mapStateToProps, actions)(my ...

Invalid prop type: A form field received a `checked` prop without a corresponding `onChange` handler

In my project, I have a Parent Component called CandidateList and a Child Component called Candidate. The CandidateList component has a Select All checkbox that triggers a function to set the state when candidates are being selected, and then passes that s ...

Is it possible to leverage specific client-side Javascript APIs on the server-side?

Exploring APIs designed for web browsers that require their .js code to return audio streams. In a broader sense, these APIs provide byte streams (such as audio) for playback in the browser. Is it possible to use these APIs in server-side Javascript frame ...

Rails assets folder is not directed to the specified directory in the layout file

I have a dilemma in the application layout where I'm referencing assets (js, css, and img) in the public/assets/... directory. For example: <link href='assets/images/meta_icons/apple-touch-icon-144x144.png' rel='apple-touch-icon-pre ...

During the rendering process, the property "quote" was accessed, however, it is not defined on the current instance. (Vue.js)

Every time I try to retrieve data from the kanye API, I encounter this error message: Property "quote" was accessed during render but is not defined on instance. Below is the code snippet that triggered the error: <template> <div> ...

Why doesn't using 'await' have any effect in NextJS API Routing?

I'm currently working on fetching data from the YouTube Data API through a NextJS Api Route, intended to be used as a cron function. While attempting to retrieve data using the await keyword in the getPlaylistData() function, I keep encountering an e ...

ejs forEach function encountering issues with JSON data in Node

When trying to iterate a JSON file in EJS using Node.js, I am getting an error that says "forEach is not a function". Below are the three sections showing what I have done in the .ejs file, JSON file, and Node.js code. This is my JSON Data ...

Handling updates and errors when using Mongoose and MongoDB

I am a bit confused about the return value of updating documents in MongoDB and how to effectively handle errors that may occur. Currently, I am utilizing Node.js, Express.js, and Mongoose.js as my primary MongoDB driver. After reviewing various tutorial ...

Astro Project experiencing issues with loading SRC folder and style tags

After setting up a brand new astro repository with the following commands: npm create astro@latest npm run dev I encountered an issue where the default project template failed to display correctly on my computer. Here is how the page appeared: https://i. ...

Pass the object either in JSON format or as a variable using the drag and drop feature

Here's a quick question: when using the Drag and Drop system, I'm not sure which method is better. Is it more efficient to : utilize setData and getData to transfer a JavaScript object? (Utilizing JSON conversion since setData only passes st ...

The method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not provide any output

After running all JavaScript, I need to retrieve the HTML content. However, I am facing an issue using WebKit.NET where the method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not return anything, even with a simple alert(). When I try passi ...

Having trouble looping through an array of objects containing images in Javascript?

I am currently facing challenges with iterating through an array of objects that contain images. The array appears empty when logged in the console, but upon inspecting it in the console, I can see all the objects along with their iteration numbers. I have ...

Troubleshooting a Non-Responsive React onClick Event in ES6

I am a beginner in React and have been searching on various platforms like StackOverflow and the internet, but I cannot figure out why onClick is not working in my case. When I click the button, absolutely nothing happens. I have tried everything from putt ...

Tips for transferring a function from a Node.js server to a client

Hey everyone, I'm trying to achieve the following: On the Node server side: var fn = function(){ alert("hello"); } I am looking for a way to send this function to the client side. I am currently using AngularJS, but I am open to other solution ...

Issue with Firebase V9 addDoc: No indication of success or failure, and data is not being written to the

I am encountering an issue where the authentication related functions are working fine, but I am unable to make any progress with Firestore. Despite no errors or successes being returned by the try-catch block, nothing seems to happen in the Firestore data ...

Steps to utilize the POST method with Angular, NodeJs/ExpressJs, and MySQL:

I am facing an issue with my Angular project where the GET method works fine, but when I try to call the POST method it seems like the POST function in Node.js is not getting called. Can someone help me figure out what I am doing wrong? Below are the snip ...

Using HTML and C# to Deliver Emails

I've encountered a challenge with my HTML page that includes a textbox for users to input their email. When the submit button is clicked, an email should be sent to a specific email address defined in the code, and a pop-up box indicating "Email Sent" ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...

React encountered an error stating that the function setCreateType is not defined, resulting in a TypeError

import React from 'react'; export const AddChannel = ({ setType, setCreatingStatus, setIsEditingFlag, updateToggleContainer, currentType }) => ( <svg width='14' height='14' viewBox='0 0 14 14' ...

Issue with jQuery: Function not triggered by value selection in dynamically created select boxes

I am in need of some assistance with my code that dynamically generates select drop down menus. I want each menu to trigger a different function when an option is selected using the "onchange" event, but I am struggling to implement this feature. Any hel ...