在JSON文件中存储inputform的值

lsmd5eda  于 2023-05-08  发布在  其他
关注(0)|答案(1)|浏览(90)

我是使用Express的新手,希望将输入字段的值存储在JSON文件中。我收到以下错误消息:POST http://localhost:5500/userData 405(Method Not Allowed)据我所知,这应该是一个问题,服务器不支持我的路径请求?我的代码在3个不同的文件中,server.js,index.html和user.js
感谢您的评分
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); // Pushes the user to the array of users
  console.log(users); // Logs the updated array of 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()); // enable 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}!`));
7cwmlq89

7cwmlq891#

我修正了你的代码

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

 const port = 5500;

 app.use(cors()); // enable CORS

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

 app.use(express.static(__dirname + '/public'));

 app.get('/',(req,res)=>{

  res.sendFile('index.html');
  });

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

  console.log(data);
  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}!`));







  <!DOCTYPE html>
  <html>
  <head>
  <title>Page Title</title>
  </head>
  <body>

   <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.di 
         splay='none'">here</Button></span>
      </form>

     <script>

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

  let user = {
   name: userName.value,
   password: userPassword.value
   }
   console.log(user);
   fetch("http://localhost:5500/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); // Pushes the user to the array of users
   console.log(users); // Logs the updated array of users
  })
  .catch(err => console.error(err));
   }

    document.getElementById('form').addEventListener('submit', (e) 
 => 
{
    e.preventDefault();
 });
  </script>
  </body>
  </html>

相关问题