简体   繁体   中英

Node, Express, vanilla JS POST form not sending data to API

I am using Node JS and Express JS to make a form submission push data to the database.

This is my form

<form action="/pokedex/register/poke_submission" method="POST">
                <div>
                    <label for="name">Pokemon</label>
                    <input type="text" name="name" id="name" required />
                </div>
                <div>
                    <label for="number">Number</label>
                    <input type="text" name="number" id="number" required />
                </div>
                <div>
                    <label for="primaryType">Primary Type</label>
                    <input
                        type="text"
                        name="primaryType"
                        id="primaryType"
                        required
                    />
                </div>
                <div>
                    <label for="secondayType">Secondary Type</label>
                    <input type="text" name="secondayType" id="secondayType" />
                </div>

This is my POST API

app.post("/pokedex/register/poke_submission", async function (req, res) {
    const poke = new Pokemon({
        information: {
            name: req.body.name,
            dexNumber: req.body.dexNumber,
            primaryType: req.body.primaryType,
            secondaryType: req.body.secondaryType, // Not required
    });
    try {
        const newPokemon = await poke.save();
        res.send(newPokemon);
    } catch (err) {
        res.send(req.body);
        console.log(err);
    }
});

and I am using these two

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

When I hit Submit, it sends me to /pokedex/register/poke_submission but with a 405 error.

It seems it should be as below in code:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

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