Struggling to move forward with developing a task management app due to a roadblock

I am seeking guidance rather than a direct answer, as this is crucial for my final exam. I require a starting point to help me fill in the missing pieces. It's important to note that local storage cannot be used to store user input.

// POST handler adds a task to a list
app.post('/task', (req, res) => {
res.set('Content-Type', 'application/json');

/*
    Input: data coming into this handler will be in the form:

    {"task": "mytask"}

    You can see contents of the incoming request with:
    console.log(req.body.task). "req" is the request
    and within it, the property req.body holds the incoming data
    above from the client request, hence "task" is a property of
    that incoming request data object.

    Output: This handler should send the datastore back to
    the client with a 201 response code if successful, and return
    and 400 response code with no response body if the task already
    exists in either the TODO or Completed list.
*/

console.log(req.body.task);

/*
    YOUR CODE HERE
*/

// send 201 status with no response body
res.status(201).send({})
});

I have multiple tabs open with various articles on node and post methods, but grasping the concept proves to be challenging at times.

Here is what I have for datastore:

let taskDatastore = {
"todo": [
    "finish test 2",
],
"completed": [
    "read the test instructions",
],
};

Answer №1

To begin, retrieve the task from the request body. Next, verify if the task is present in either the todo or completed arrays and return the appropriate status codes in the response.

// This POST handler is responsible for adding a task to a list
app.post('/task', (req, res) => {
  res.set('Content-Type', 'application/json');

  /*
      Input: The data received by this handler will be structured as follows:

      {"task": "mytask"}

      You can view the contents of the incoming request using:
      console.log(req.body.task). "req" represents the request
      and within it, the property req.body contains the incoming data
     above from the client request, hence "task" is a property of
      that incoming request data object.

      Output: If successful, this handler should send the datastore back to
      the client with a 201 response code. If the task already exists
      in either the TODO or Completed list, it should return
      a 400 response code with no response body.
  */


  let taskDatastore = {
    "todo": [
      "finish test 2",
    ],
    "completed": [
      "read the test instructions",
    ],
  };

  const task = req.body.task;

  // Verify if the task already exists in the TODO or COMPLETED arrays
  if (taskDatastore.todo.includes(task) || taskDatastore.completed.includes(task)) {
    // Send a 400 status with no response body
    res.status(400).send({});
  } else {
    // Send a 201 status with the datastore in the response body
    res.status(201).send(taskDatastore);
  }
});

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

Why is the express-session cookie being transmitted by the API but not detected by the browser?

Despite sending the cookie in express session via API, it is not being picked up by the browser, leading to a new session being generated for each API call. I am currently utilizing express-session with an Express backend and Vue frontend. Below is a con ...

Angular filtering options based on user input and model selection

In the jsbin demo provided, there is an input field, a select option, and a list of movies. The objective is to filter the list of movies in Angular based on user input in the input field and selection in the select dropdown. <div ng-controller="myCont ...

"Unleashing the power of ng-options in AngularJS: a guide to dynamically retrieving the index

I am currently working with a select element, where I need both the selected value and dynamically generated index (I do not want to set the default index to [0]). How can this be achieved? <div class="input-label"> Select Mobile ...

Heroku local is designed to support only NodeJS applications, without any Angular framework or database connectivity

I'm currently facing two separate issues. When I run my app locally, it works fine, but it doesn't function properly on Heroku. Running "heroku local" opens the NodeJS app on localhost:5000 and connects to the local database. However, when attemp ...

How about I visit the campgrounds/edit page for a change?

In this get route, the previous link it was redirected from is stored in the req.session object under returnTo. Once redirected, it goes to the /login and we are able to view the object in the console. router.get('/login', (req, res) => { ...

Differences Between jQuery Ajax POST Settings and GET Settings

I am in the process of developing a compact plug-in with a strong emphasis on code efficiency and stability. The issue is clearly outlined within the code snippet provided below (further explanation can be found underneath): $(document).ajaxSend(fun ...

Is there a way to track when the Angular DTOptionsBuilder ajax call is complete and trigger a callback function?

Working with angular datatables, I have the following code: beforeSend:</p> success callback causes the table on the page not to populate with the data. How can I implement a callback that triggers once the ajax is done without interfering with the ...

React Ant Design: Encountered a warning for 2 elements having non-unique properties

I have incorporated the Carousel component, with each one containing a different component. One contains a form, while the other includes an external library component called react-input-otp. https://codesandbox.io/s/pensive-einstein-uucvm?fontsize=14& ...

Tips for adjusting the font size of choices within the Material UI autocomplete component

Hey there, I'm currently working on a project using the Material Table and I'm looking to adjust the font size of the options in the Material UI Autocomplete. Any tips would be greatly appreciated! Thanks https://i.sstatic.net/ZM17w.png import R ...

What is the mechanism by which nodes handle multiple requests simultaneously?

Lately, I've delved into the world of NodeJs, trying to grasp how it handles multiple concurrent requests. It's fascinating that NodeJs operates on a single-threaded event loop architecture, where only one statement executes at a time on the main ...

JavaScript form validation: returning focus to textfields

I am currently working on a project where I am using JQuery and JavaScript to create an input form for time values. However, I am facing challenges in getting the JavaScript code to react correctly when incorrect input formats are detected. I have a group ...

The app.use function encountered an error stating "Cannot modify header information - headers already sent"

Within my app.js file, I have the following code snippet: app.use(function(req, res, next){ if(!req.user){ res.redirect('/login_'); } next(); }) Upon reviewing the above code, everything appears to be correct. In my route/index.js fi ...

Issue encountered when attempting to push jQuery AJAX requests into an array

I'm attempting to store ajax requests in an array called deferreds. However, I'm consistently encountering the error message below: Uncaught SyntaxError: missing ) after argument list As a reference, I've been using this guide: Pass in an ...

Error code E401 is being encountered with npm, indicating either an incorrect password has been provided or the

My Node version is 10.15.0 and my NPM version is currently at 6.8.4. After updating npm to 14.16.0 and node to 7.6.2, I encountered the following error - npm ERR! code E401 npm ERR! Incorrect or missing password. npm ERR! If you were trying to log in, ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

Storing an ID field across different domains using HTML and JavaScript: Best Practices

Currently, my web app includes a conversion tracking feature that analyzes whether activity "A" by a website visitor leads to action "B." This feature works effectively when the tracking is contained within a single domain but encounters issues across mul ...

Steps to live stream data from a Node.js server to a client

I am currently facing a challenge with sending a large CSV file that needs to be processed in the browser. My goal is to stream the file to the client to avoid exceeding string size limits and to reduce memory usage on the server. So far, I have attempte ...

Loop through the numbers entered into a table field

<table id="Container1Details" cellspacing="15"> <tbody> <tr> <td align="right"> <input name="acidity" type="number" maxlength="4" id="acidity" min="0.112" max="0.152" step="0.001" style= ...

Is there a way to automatically override the CSS cursor style?

Issue with SCSS styling on image link I attempted to modify the cursor style from pointer to default, but after saving and reloading my React app, the change did not take effect. I tried writing some code, but it seems that Stack Overflow is indicating an ...

Utilizing JavaScript to present JSON data in HTML tables across various sections of a website

Utilizing JScript to retrieve data from a JSON API URL, I have incorporated the data in the JSON file displayed below - containing information on 8 horse races with details like Horse number, Horse name, and their odds. My goal is to create a Jscript code ...