簡體   English   中英

Javascript 不允許發布請求方法

[英]Javascript post request method not allowed

我正在嘗試在 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 請求上,當我執行任何其他請求時它工作正常。 有什么解決辦法嗎?

你的JS不正確

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM