NodeJS 为什么我的Express服务器在提交表单时返回404而不显示console.log消息?

bnl4lu3b  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(155)

正在尝试创建多用户会话(想想谷歌文档)但是由于某种原因我的服务器文件没有做任何事情,我已经确保我的fetch函数是正确的,但什么也没有改变。甚至console.log从服务器文件命令没有显示。我不知道我错过了什么。我也使用了随机链接生成器函数,但我不认为这是相关的,因为链接生成正确,不过我还是会把它包含在我的代码中。
Server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());


app.post('/api/session', (req, res) => {
    const name = req.body.name;
    const sessionLink = req.body.sessionLink;
  
    // Create a data object to store the name and session link
    const data = {
      name,
      sessionLink,
    };
  
    // Write the data to a file
    fs.writeFile('data.json', JSON.stringify(data), (err) => {
      if (err) {
        console.error(err);
        res.status(500).send('Error writing to file');
      } else {
        res.send('Success');
      }
    });
  });
  
  app.listen(3000, (error) => {
    if (error) {
      console.log('Error starting server:', error);
    } else {
      console.log('Server is listening on port 3000');
    }
  });

mainpage.js

const generateSessionLink = () => {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 8; i++) {
      result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return 'https://mywebsite.io/session/' + result;
  };

 
  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  const handleSessionLinkChange = (event) => {
    setSessionLink(event.target.value);
  };

  const handleEnterSession = () => {
    if (name.trim() === '') {
      alert('Please enter your name or nickname.');
      return;
    }
    
  
    if (sessionLink.trim() === '') {
      alert('Please enter a session link or join an existing one.');
      return;
    }
  
    // Make a POST request to the session endpoint
    fetch('/api/session', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name,
        sessionLink
      })
    })
    .then(response => {
      if (response.ok) {
        // Store the name and session link in local storage
        localStorage.setItem('name', name);
        localStorage.setItem('sessionLink', sessionLink);
  
        // Redirect to the app page
        window.location.href = "/app";
      } else {
        throw new Error('Network response was not ok');
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('An error occurred while trying to join the session. Please try again later.');
    });
  };
x4shl7ld

x4shl7ld1#

我试过你的代码,你唯一做错的是获取URL,因为节点服务器没有运行在与你的页面相同的端口/主机上。如果这仍然不能解决你的问题,那么你必须检查浏览器控制台,那里可能有更多的信息。

fetch('http://localhost:3000/api/session', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name,
        sessionLink
      })
    })

相关问题