Node-RED中展示MQTT接收的原始JSON数据失败:GET请求返回JS代码
Hey there! Let's get your IoT data showing up in a web page properly—you're already doing the hard part by getting MQTT data parsed into JSON, so we just need to tweak how Node-RED serves that data to your browser.
The Likely Issue
When you get JavaScript code instead of a data-displaying web page, it usually means your Node-RED flow is either:
- Returning raw Node-RED function code by accident,
- Serving JSON data directly without wrapping it in an HTML template,
- Or misconfiguring the HTTP response to send JavaScript instead of HTML.
Step-by-Step Solution
1. Store Your Latest IoT Data
First, we need to keep track of the most recent MQTT data so the web page can fetch it on demand. Add a Change node right after your JSON node:
- Set the operation to
Set - Target:
global.set("latestIoTData", msg.payload)(this saves the JSON data to Node-RED's global context)
2. Build an HTTP Endpoint for the Web Page
Next, create a flow that serves an HTML page with your data:
- Drag an HTTP In node onto the canvas. Configure it with:
- Method:
GET - URL:
/iot-dashboard(or any path you prefer)
- Method:
- Add a Template node connected to the HTTP In node. Paste this HTML template into the node (it uses Handlebars syntax to render your data):
<!DOCTYPE html> <html> <head> <title>My IoT Dashboard</title> <style> body { font-family: 'Arial', sans-serif; padding: 2rem; max-width: 600px; margin: 0 auto; } .sensor-data { background: #f0f8ff; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .data-row { margin: 0.8rem 0; } .data-label { font-weight: bold; color: #2c3e50; } </style> </head> <body> <h1>Latest IoT Sensor Readings</h1> <div class="sensor-data"> {{#if global.latestIoTData}} {{#each global.latestIoTData}} <div class="data-row"> <span class="data-label">{{@key}}:</span> {{this}} </div> {{/each}} {{else}} <p>No data received yet—wait for your MQTT broker to send messages!</p> {{/if}} </div> </body> </html> - Connect the Template node to an HTTP Response node. Important: In the HTTP Response node's settings, set the Return type to
text/html(this tells browsers to render it as a web page instead of raw text/JSON).
3. Deploy and Test
- Deploy your updated flow.
- Open your browser and go to
http://<your-node-red-ip>:1880/iot-dashboard(replace<your-node-red-ip>with your Node-RED device's IP, likelocalhostif you're running it locally).
You should now see a clean web page showing your latest IoT data!
Bonus: Real-Time Updates (No Page Refresh)
If you want the data to update automatically without refreshing the page, you can add a WebSocket Out node after your Change node, and modify the HTML template to listen for WebSocket messages. But that's an extra step—let's get the basic display working first!
内容的提问来源于stack exchange,提问作者Guille Ruiz Gonzalez

