简体   繁体   English

从服务器向客户端发送数据

[英]send data from server to client

hello I got JSON data from axios request and I wanna send it from server to client I converted it into JSON string and I send it with app.get and I tried to catch it with fetch in HTML script but i got an error in the browser "Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse ()" axios.get work properly and it returns the response!你好,我从 axios 请求中获得了 JSON 数据,我想将它从服务器发送到客户端我将它转换为 JSON 字符串,然后用 app.get 发送它,我试图用 HTML 脚本中的 fetch 来捕获它,但我在浏览器中遇到了错误"Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse ()" axios.get 正常工作并返回响应! i think i have a problem with the app.get in server or fetch() in index.html我想我在服务器中的app.get或 index.html 中的fetch()有问题

server.js服务器.js

const express = require('express');
const app = express();
app.listen(3000, );
app.use(express.static('public'));

const axios = require('axios')
const username = 'admin'
const password = 'admin'
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const urlLAMP_0 = 'http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la'
const urlLAMP_1 = 'http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la'
function getDataLAMP_0(){
  axios.get(urlLAMP_0, {
    headers: {
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Origin':'*',
      "X-M2M-RI":"OM2M-webpage",
      'Authorization': `Basic ${token}`,
      'Accept': 'application/json',
      'mode': 'cors',
      'credentials': 'include',
      }
  })
  .then(function(response) {
        const jsondata = JSON.stringify(response.data['m2m:cin']);
        app.get('/', (req, res)=>{
        res.send(jsondata)
        })
    return response;
  })
}

public/index.html公共/index.html

<title> LAMP DATA </title>

<style>
    * {
  font-family: sans-serif; 
}
h1 {
  color: #009879;
  font-size: 300%;
  text-align: center;;
}

.content-table {
  
  border-collapse: collapse;
  margin: 25px 0;
  font-size: 0.9em;
  min-width: 400px;
  border-radius: 5px 5px 0 0;
  overflow: hidden;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}

.content-table thead tr {
  background-color: #009879;
  color: #ffffff;
  text-align: left;
  font-weight: bold;
}

.content-table th,
.content-table td {
  padding: 12px 15px;
}

.content-table tbody tr {
  border-bottom: 1px solid #dddddd;
}

.content-table tbody tr:nth-of-type(even) {
  background-color: #f3f3f3;
}

.content-table tbody tr:last-of-type {
  border-bottom: 2px solid #009879;
}


</style>

<body>
    <h1> lamp Data </h1>
    <table class="content-table">
        <thead>
          <tr>
            <th>Name</th>
            <th>rn</th>
            <th>ty</th>
            <th>ri</th>
            <th>pi</th>
            <th>ct</th>
            <th>lt</th>
            <th>st</th>
            <th>cnf</th>
            <th>cs</th>
            <th>con</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>LAMP_0</td>
            <td><span id="rn0"></span></td>
            <td><span id="ty0"></span></td>
            <td><span id="ri0"></span></td>
            <td><span id="pi0"></span></td>
            <td><span id="ct0"></span></td>
            <td><span id="lt0"></span></td>
            <td><span id="st0"></span></td>
            <td><span id="cnf0"></span></td>
            <td><span id="cs0"></span></td>
            <td><span id="con0"></span></td>
          </tr>
          <tr>
            <td>LAMP_1</td>
            <td><span id="rn1"></span></td>
            <td><span id="ty1"></span></td>
            <td><span id="ri1"></span></td>
            <td><span id="pi1"></span></td>
            <td><span id="ct1"></span></td>
            <td><span id="lt1"></span></td>
            <td><span id="st1"></span></td>
            <td><span id="cnf1"></span></td>
            <td><span id="cs1"></span></td>
            <td><span id="con1"></span></td>
          </tr>
        </tbody>
      </table>
  <script>
    fetch('/')
    .then(function(response) {
      console.log(response)
      const jsondata = JSON.parse(response);
        document.getElementById("rn0").textContent = jsondata['m2m:cin'].rn;
        /*document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
        document.getElementById("ri0").textContent = response.data['m2m:cin'].ri;
        document.getElementById("pi0").textContent = response.data['m2m:cin'].pi;
        document.getElementById("ct0").textContent = response.data['m2m:cin'].ct;
        document.getElementById("lt0").textContent = response.data['m2m:cin'].lt;
        document.getElementById("st0").textContent = response.data['m2m:cin'].st;
        document.getElementById("cnf0").textContent = response.data['m2m:cin'].cnf;
        document.getElementById("cs0").textContent = response.data['m2m:cin'].cs;
        document.getElementById("con0").textContent = response.data['m2m:cin'].con;*/
        return response;
  })
  </script>
</body>

Express routes like app.get should be at the top level.app.get这样的 Express 路由应该在顶层。 So the implementation would look something like this所以实现看起来像这样


const express = require("express");
const app = express();
const axios = require("axios");

app.listen(3000, () => console.log("server is running"));

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

  // The rest of your code here ....

});

Try to get the Idea in CodeSandbox尝试在CodeSandbox 中获取想法


code sample代码示例

 const express = require("express"); const app = express(); const axios = require("axios"); app.listen(3000, () => console.log("server is running")); app.get("/", async(req, res) => { try { const username = "admin"; const password = "admin"; const token = Buffer.from(`${username}:${password}`, "utf8").toString( "base64" ); const urlLAMP_0 = "http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la"; const urlLAMP_1 = "http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la"; const response = await axios.get(urlLAMP_0, { headers: { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Origin": "*", "X-M2M-RI": "OM2M-webpage", Authorization: `Basic ${token}`, Accept: "application/json", mode: "cors", credentials: "include" } }); return res.status(200).json(response.data); } catch (err) { console.log(err.message); return res.status(500).json("something went wrong"); } }); app.use(express.static("public"));
 <title>LAMP DATA</title> <style> * { font-family: sans-serif; } h1 { color: #009879; font-size: 300%; text-align: center; } .content-table { border-collapse: collapse; margin: 25px 0; font-size: 0.9em; min-width: 400px; border-radius: 5px 5px 0 0; overflow: hidden; box-shadow: 0 0 20px rgba(0, 0, 0, 0.15); } .content-table thead tr { background-color: #009879; color: #ffffff; text-align: left; font-weight: bold; } .content-table th, .content-table td { padding: 12px 15px; } .content-table tbody tr { border-bottom: 1px solid #dddddd; } .content-table tbody tr:nth-of-type(even) { background-color: #f3f3f3; } .content-table tbody tr:last-of-type { border-bottom: 2px solid #009879; } </style> <body> <h1>lamp Data</h1> <table class="content-table"> <thead> <tr> <th>Name</th> <th>rn</th> <th>ty</th> <th>ri</th> <th>pi</th> <th>ct</th> <th>lt</th> <th>st</th> <th>cnf</th> <th>cs</th> <th>con</th> </tr> </thead> <tbody> <tr> <td>LAMP_0</td> <td><span id="rn0"></span></td> <td><span id="ty0"></span></td> <td><span id="ri0"></span></td> <td><span id="pi0"></span></td> <td><span id="ct0"></span></td> <td><span id="lt0"></span></td> <td><span id="st0"></span></td> <td><span id="cnf0"></span></td> <td><span id="cs0"></span></td> <td><span id="con0"></span></td> </tr> <tr> <td>LAMP_1</td> <td><span id="rn1"></span></td> <td><span id="ty1"></span></td> <td><span id="ri1"></span></td> <td><span id="pi1"></span></td> <td><span id="ct1"></span></td> <td><span id="lt1"></span></td> <td><span id="st1"></span></td> <td><span id="cnf1"></span></td> <td><span id="cs1"></span></td> <td><span id="con1"></span></td> </tr> </tbody> </table> <script> (function() { fetch("/") .then(function(response) { return response.json(); }) .then(function(data) { console.log(data); // const jsondata = JSON.parse(data); document.getElementById("rn0").textContent = data[0].body; // document.getElementById("rn0").textContent = jsondata["m2m:cin"].rn; /*document.getElementById("ty0").textContent = response.data['m2m:cin'].ty; document.getElementById("ri0").textContent = response.data['m2m:cin'].ri; document.getElementById("pi0").textContent = response.data['m2m:cin'].pi; document.getElementById("ct0").textContent = response.data['m2m:cin'].ct; document.getElementById("lt0").textContent = response.data['m2m:cin'].lt; document.getElementById("st0").textContent = response.data['m2m:cin'].st; document.getElementById("cnf0").textContent = response.data['m2m:cin'].cnf; document.getElementById("cs0").textContent = response.data['m2m:cin'].cs; document.getElementById("con0").textContent = response.data['m2m:cin'].con;*/ }); })(); </script> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM