不允许使用 Javascript 发布请求方法

时间:2021-06-10 22:00:11

标签: javascript http-post http-status-code-405

我正在尝试使用 javascript 制作身份验证应用程序,但出现 405 Method not allowed 错误。

    <form id="main-form" name="main-form">
        <input id="username" autocomplete="off">
        <input id="password" autocomplete="off" type="password">
        <input id="password-confirm" autocomplete="off" type=password>
        <input  id="register-proceed" type="submit" value="REGISTER">
        <script src="js/auth/register.js"></script>
    </form>

js 文件:

const form = document.getElementById('main-form')

form.addEventListener('submit', registerUser)

async function registerUser(event) {
    
    event.preventDefault()
    const username = document.getElementById('username').value
    const password = document.getElementById('password').value

    await fetch('/api/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username,
            password
        })
    })

}


编辑:我添加了后端代码:

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

const app = express()
app.use('/', express.static(path.join(__dirname, 'static')))
app.use(bodyParser.json())
app.post('/api/register', async (req, res) => {
    console.log(req.body)
    res.json( {status: "ok"})
})

app.listen(9999, () => {
    console.log("Server up at port 9999")
})

编辑:我发现问题出在 POST 请求上,当我执行任何其他请求时,它工作正常。有什么解决办法吗?

1 个答案:

答案 0 :(得分:0)

你的JS不正确

fetch('/api/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            "username": "YOUR_USERNAME",
            "password": "YOUR_PASSWORD"
        })
    })