繁体   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