簡體   English   中英

嘗試向我的節點服務器發送請求時出現錯誤 405“方法不允許”

[英]getting error 405 'Method not Allowed' When trying to send request to my node server

這是我第一次使用 Express 和 MongoDB,我創建了我的節點服務器並將其連接到我的 mongoDB 數據庫,但是當我嘗試從我的 html 頁面向服務器發送請求時,我得到錯誤 405 方法不允許,以下是我的 node.js服務器代碼

 mongoose.connect('mongodb://localhost/userdatabase',{ useNewUrlParser: true, useUnifiedTopology: true }) const app = express() app.use('/', express.static(path.join(__dirname, 'static'))) app.use(bodyParser.json()) const port = 5500 app.listen(port, () => { console.log(`server is up at ${port}`) }) app.post('/api/register', async(req, res) => { const {username, password} = req.body res.json({status: 'ok'}) try{ const response = await User.create({ username, password }) console.log('User created succesfully', response) }catch(error){ console.log(error) } })

這里是 function 我試圖打電話來做發帖請求

 const form = document.querySelector('#register') form.addEventListener('submit', registerUser) async function registerUser(event){ event.preventDefault() const username = document.getElementById('username').value const password = document.getElementById('password').value const result = await fetch('/api/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }).then(res => res.json()) }

基本上我正在創建一個登錄系統並嘗試注冊用戶,但由於某種原因我在嘗試調用服務器時不斷收到錯誤 405,請注意由於某種原因它在我之前嘗試時工作了 3 次,我幾乎沒有改變任何東西在代碼中但它不會工作,它可以是什么? 提前致謝

您應該告訴 mongoDB 將在哪個端口運行。

const mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://localhost:27017/test');
}

我認為您必須在調用 axios 時聲明服務器和端口。axios 調用應該是 - await fetch('localhost:5500/api/register') 它正在搜索“/api/register”但沒有找到任何內容。 希望這能解決您的問題。

問題已解決:html 文件不在“static”文件夾中,可能我已經移動了它但沒有注意到,對不起,伙計們,如果有人遇到同樣的問題,請務必檢查一下

暫無
暫無

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

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