首页 > 解决方案 > Node.js 项目设置方法有问题

问题描述

我无法弄清楚/找到有关如何执行此操作的任何信息。这是一个学校项目,我们正在制作一个待办事项列表,您可以在其中添加、删除、更新和查看您当前的所有待办事项。

我遇到的问题在此代码中:

//*Check if method is post
    if (request.method.toLowerCase() === 'post') {
        //*Check so the searchparam todo exists
        if (url.searchParams.get('todo')) {
            //*Get the submitted todo
            let todo = url.searchParams.get('todo');

            //*Add the todo and send success message
            todoDB.add(todo);
            success(todo);
        } else {
            fail("Parameter 'todo' does not exist or is empty");
        }
    }

检查请求方法是否为“post”的 if 语句是我遇到的问题,我不知道如何将方法设置为 POST。该代码块应该向数据库添加一个待办事项,该待办事项是通过一个参数提供的:localhost/todolist?todo=MyTodo。但是我如何将请求方法设置为 POST 以便它实际发布?

我已经看到你可以使用选项等来设置方法,但是这个程序应该使用这些方法:POST、GET、PUT、DELETE。我现在有点坚持如何去做。任何帮助表示赞赏,如果有任何帮助,我将在此处包含所有代码。

import http from 'http';
import fs from 'fs';
import path from 'path';
import TodoList from './TodoList.js';

const port = 80;
const host = 'http://localhost';

const todoDB = new TodoList();

//* Add todos for debug purposes
todoDB.add('Eat');
todoDB.add('Sleep');
todoDB.add('Chill');

//*Listener to listen for http requests
const listener = (request, response) => {    

    let url = new URL(request.url, host);

    //*Log information    
    console.log('Url: ', request.url);
    console.log('Path: ', url.pathname);
    console.log('Method: ', request.method);
    console.log('Query params: ', url.searchParams.keys());
    console.log('Header params: ', request.headers);

    let data;

    //*Fail function to send user error messages
    function fail(error) {
        response.writeHead(404, { 'Content-Type': 'application/json' });

        data = {
            status: 'fail',
            error: error,
        };
    }

    //*Success function to send user success message
    function success(responseData) {
        response.writeHead(200, { 'Content-Type': 'application/json' });

        data = {
            status: 'success',
            data: responseData,
        };
    }

    //*First check if user is in /todolist path
    if (url.pathname === '/todolist') {
        //*Check if method is post
        if (request.method.toLowerCase() === 'post') {
            //*Check so the searchparam todo exists
            if (url.searchParams.get('todo')) {
                //*Get the submitted todo
                let todo = url.searchParams.get('todo');

                //*Add the todo and send success message
                todoDB.add(todo);
                success(todo);
            } else {
                fail("Parameter 'todo' does not exist or is empty");
            }
        }

        //*Check if method is get
        else if (request.method.toLowerCase() === 'get') {
            //*Check so search param is id exists
            if (url.searchParams.get('id')) {
                //*Get the id from param
                let id = url.searchParams.get('id');

                //*Parse to int and get todo with correct id
                let todo = todoDB.get(parseInt(id));

                //*Send message to user
                success(todo);
            } else {
                //*Since we didn't get an ID, we'll show all todos
                success(todoDB.getAll());
            }
        }
        //*The user entered a method that isn't supported
        else {
            fail('Method ' + request.method + ' is not supported');
        }
    }

    //*User is in wrong path
    else {
        fail('Path ' + url.pathname + ' is not supported');
    }

    response.write(JSON.stringify(data));
    response.end();

    console.log('DB', todoDB.getAll());
};

//*Declare server and listen on the port
const server = http.createServer(listener);
server.listen(port);

标签: node.jsmethodsparameters

解决方案


我解决了,老师忘记提到我们应该使用“邮递员”向它发送API请求的部分。


推荐阅读