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

Node.js服务端与客户端Ajax请求异常:写入文件无响应

Troubleshooting Your Unresponsive Server Request & File Write Issue

Hey there! Let's break down why your server isn't reacting to the client's button click and failing to write to ouss.txt—I've got a few key fixes to get this working smoothly.

First, Let's Spot the Core Issues in Your Current Code

Looking at the snippet you shared, there are three critical missing pieces causing the problem:

  1. No HTTP Server Setup: Your code has the on() function to write the file, but there's no logic to listen for client requests (like the button click). Right now, your server isn't even set up to receive incoming traffic, so the client's request just dies out.
  2. Undefined etat Variable: The code checks if (etat=="1"), but where is etat coming from? It needs to be extracted from the client's request (like a POST body or URL parameter)—right now, this variable is empty, so on() never gets called.
  3. No Client Feedback: Even if the file write worked, your server doesn't send any response back to the client, so you'd never know if it succeeded or failed.

Here's a Fixed, Working Implementation

Let's use Express (a popular Node.js framework) to build a proper server that handles client requests, processes the etat value, writes to the file, and sends clear feedback.

Step 1: Set Up the Project

First, initialize your project and install dependencies:

npm init -y
npm install express cors

Step 2: Full Server Code (server.js)

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

// Allow cross-origin requests (if your client is on a different port/domain)
app.use(cors());
// Parse incoming JSON/form data from the client
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Define a route to handle the GPIO toggle request
app.post('/toggle-gpio', (req, res) => {
  // Extract the 'etat' value from the client's request body
  const etat = req.body.etat;

  // Validate the input to avoid invalid requests
  if (!['1', '0'].includes(etat)) {
    return res.status(400).send('Invalid value! Use "1" for ON, "0" for OFF');
  }

  // Call the appropriate function, passing the response object to send feedback
  etat === '1' ? on(res) : off(res);
});

function on(res) {
  fs.writeFile('ouss.txt', '1', (err) => {
    if (err) {
      console.error('File write error:', err);
      return res.status(500).send('Failed to turn GPIO ON (file write error)');
    }
    console.log('GPIO ON - File updated!');
    res.status(200).send('GPIO turned ON successfully');
  });
}

function off(res) {
  fs.writeFile('ouss.txt', '0', (err) => {
    if (err) {
      console.error('File write error:', err);
      return res.status(500).send('Failed to turn GPIO OFF (file write error)');
    }
    console.log('GPIO OFF - File updated!');
    res.status(200).send('GPIO turned OFF successfully');
  });
}

// Start the server
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Step 3: Client Button Code Example

Add this to your client HTML to send requests when buttons are clicked:

<button id="onButton">Turn GPIO ON</button>
<button id="offButton">Turn GPIO OFF</button>

<script>
// Helper function to send requests to the server
async function sendToggleRequest(etat) {
  try {
    const response = await fetch('http://localhost:3000/toggle-gpio', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ etat: etat })
    });
    const message = await response.text();
    alert(message); // Show clear feedback to the user
  } catch (error) {
    console.error('Request failed:', error);
    alert('Failed to connect to server');
  }
}

// Attach click handlers to buttons
document.getElementById('onButton').addEventListener('click', () => sendToggleRequest('1'));
document.getElementById('offButton').addEventListener('click', () => sendToggleRequest('0'));
</script>

Final Checks to Ensure It Works

  1. Start the Server: Run node server.js in your terminal—you should see the "Server running" confirmation message.
  2. Test the Buttons: Open your client HTML in a browser and click the buttons. You'll get alerts confirming success, and ouss.txt will update with '1' or '0' accordingly.
  3. File Permissions: Make sure your Node.js process has write access to the directory where ouss.txt is created.
  4. CORS: If your client is hosted on a different port (like 8080) or domain, the cors package we installed handles that automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:57:35