简体   繁体   中英

EJS: Trying to use PATCH method with html form

I have just started learning Node.js.

I have this following code where I need to submit the form using patch method to update an existing record.

Language/Edit.ejs

<form action="//localhost:3000/languages/6343eb83340e657a0321a9cc" method="post">
    ...

    <div class="boxFooter grid gap-2">
        <input type="hidden" name="_method" value="patch">
        <button type="submit">Update</button>
    </div>
</form>

Router

...
Router.patch('languages/:id', validations, update);
...

Controller

import Model from '#Models/Language.js';

...

const update = async (req, res) => {
    try {
        const item = await Model.findByIdAndUpdate(req.params.id, {
            title: req.body.title,
            description: req.body.description,
            status: req.body.status,
        }, {
            new: true,
            runValidators: true
        });

        res.send(item);
    } catch (error) {
        return res.status(400).json('Sorry, we have an error.');
    }
};

But, I am getting this error always

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>
<body>
    <pre>Cannot POST /languages/6343eb83340e657a0321a9cc</pre>
</body>
</html>

I have also tried to use method="patch" instead of method="post" . But, the outcome is still the same.

However, I tried to run this url with postman and it worked flawlessly.

Here is the peace of code that solved my problem. However, I am not sure whether this is the right way or not.

What I did was that I changed the method to patch and submitted the form with ajax.

Here is my code:

<form action="//localhost:3000/languages/6343eb83340e657a0321a9cc" method="patch">
    ...

    <div class="boxFooter grid gap-2">
        <button type="submit">Update</button>
    </div>
</form>

<script type="text/javascript">
...

ajaxRequest({
    ...
    type: $('form').attr('method'),
    ...
})
</script>
...
const ajaxRequest = (params) => {
    return $.ajax($.extend(true, {
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        type: 'POST',
        url: '',
        data: {},
        cache: false,
        beforeSend: () => {},
        success: (response) => {},
        complete: (response) => {}
    }, params));
};
...

Is this the right way..?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM