You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express入门问题:表单数据存JSON文件时遇405错误

问题:POST请求405 Method Not Allowed错误

我是Express框架新手,尝试将表单输入框的值存入JSON文件时出现错误:POST http://localhost:5500/userData 405 (Method Not Allowed),怀疑是服务器不支持该请求路径?以下是我的三个文件代码:

HTML代码

<form class="modal-form" id="form" method="post" action="/data/userData.json">
    <h1>Create your account!</h1>
    <div class="form-validation">
        <input class="modal-input" type="text" id="createUserName" name="name" placeholder="Enter your name"></input>
    </div>

    <div class="form-validation">
        <input class="modal-input" type="password" id="createUserPassword" name="password" placeholder="Enter your password"></input>
    </div>

    <Button type="submit" class="modal-input-btn" value="Sign Up" onclick="createUser()">Sign up</Button>

    <span class="modal-input-login"> Already have an account? Login <Button type="button" onclick="document.getElementById('modal-login').style.display='block',document.getElementById('modal').style.display='none'">here</Button></span>
</form>

user.js代码

let users = [];
function createUser() {
let userName = document.getElementById('createUserName');
let userPassword = document.getElementById('createUserPassword');

let user = {
name: userName.value,
password: userPassword.value
}

fetch("http://localhost:5500/data/userData", {
method: "POST",
body: JSON.stringify(user),
headers: {
  "Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => {
  console.log(json);
  users.push(user); // 将用户添加到用户数组
  console.log(users); // 打印更新后的用户数组
})
.catch(err => console.error(err));
}

document.getElementById('form').addEventListener('submit', (e) => {
e.preventDefault();
});

server.js代码

const express = require('express');
const cors = require('cors');
const fs = require('fs');
const app = express();

const port = 5500;

app.use(cors()); // 启用CORS

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

app.post('/data/userData', (req, res) => {
const data = JSON.stringify(req.body);

fs.writeFile('./data/userData.json', data, (err) => {
if (err) {
  console.error(err);
  res.status(500).send('Error writing to file');
} else {
  res.send('Data written to file');
}
});
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));
问题分析与修复

核心问题点

  1. 请求路径混淆:错误提示中的请求路径是/userData,但你实际配置的服务器路由是/data/userData,且HTML表单的action设置为/data/userData.json(服务器未配置该路径的POST路由),虽然JS里用e.preventDefault()阻止了默认表单提交,但路径不一致会导致潜在的请求错误。
  2. 响应格式不匹配:服务器返回的是纯文本响应,但前端fetch调用了response.json()解析,会引发JSON解析错误。
  3. 数据覆盖问题:当前用fs.writeFile会直接覆盖JSON文件内容,无法保存多个用户数据。

修复步骤

  1. 统一请求路径:
    移除HTML表单的action属性(已用JS处理提交,无需默认提交地址),确保前端fetch地址http://localhost:5500/data/userData与服务器路由完全一致。

  2. 修正响应格式:
    修改服务器路由的响应为JSON格式,避免前端解析错误:

    app.post('/data/userData', (req, res) => {
      // ... 其他代码
      res.json({ message: 'Data written to file' });
      // ... 其他代码
    });
    
  3. 支持多用户存储:
    修改服务器代码,先读取现有JSON文件内容,添加新用户后再写入,避免覆盖:

    app.post('/data/userData', (req, res) => {
      fs.readFile('./data/userData.json', 'utf8', (err, data) => {
        let users = [];
        if (!err) {
          users = JSON.parse(data);
        }
        users.push(req.body);
        fs.writeFile('./data/userData.json', JSON.stringify(users), (writeErr) => {
          if (writeErr) {
            console.error(writeErr);
            res.status(500).json({ error: 'Error writing to file' });
          } else {
            res.json({ message: 'Data written to file' });
          }
        });
      });
    });
    
  4. 确保目录存在:
    手动创建项目根目录下的data文件夹,否则fs.writeFile会因找不到目录报错。

内容的提问来源于stack exchange,提问作者Tange007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:35:40