Sending JSON object data to HTML side? -> 将JSON对象数据发送到HTML端?

huangapple go评论69阅读模式
英文:

Sending JSON object data to HTML side?

问题

I have made a JSON object using Node.js functions and want to send it to the HTML side to create a table with the data. However, it's not being sent over, and I'm unsure how to do it since I'm new to Node.js. When using Express to send the object and fetch in my HTML file's script, the Chrome developer tools console.log under the network tab shows as pending, and the data does not show. Postman shows the request to the localhost URL as "Sending Request."

Node.js code:

const http = require("http");
const fs = require("fs");
const url = require("url");
const express = require("express");
const app = express();
app.use(express.urlencoded({
    extended: true,
}));
app.use(express.json());
const server = http.createServer((req, res) => {
    const { query, pathname } = url.parse(req.url, true);
    if (pathname == "/") {
        res.writeHead(200, { "Content-type": "text/html" });
        const outMap = Array.from(teams)
            .map((el) => homepageTeamLister(teamsListHTML, el))
            .join("");
        res.end(outMap);
    } else if (pathname == "/player") {
        app.get("/test", function (req, res) {
            res.setHeader(
                "Access-Control-Allow-Origin",
                "http://localhost:9000/test"
            );
            res.setHeader("Access-Control-Allow-Methods", "GET");
            const myObj = { name: "John", age: 30 };
            res.send(myObj);
        });
    }
});
server.listen(9000, "127.0.0.1", () => {
    console.log("listening on port 9000");
});

HTML script code:

console.log("Entered Script");
fetch('/test')
    .then(res => res.json())
    .then(data => {
        console.log("Hi? : ", data); // { name: "John", age: 30 }
    })
    .catch(console.error);

$.ajax({
    url: 'http://localhost:9000/test',
    complete: function (data) {
        console.log(data);
    }
});

Both the fetch function and AJAX attempts did not work.

英文:

I have a made a JSON object using Node JS functions, and now I want to send this JSON object to the HTMl side so that I can make a table with the data. However, it's not being sent over, and since I am quite new to Node JS, I'm unsure how I can send this JSON object over.

When I use Express to send the object and use fetch in the script of my HTML file, the console.log in Chrome developer tools (under the network tab) shows as pending, and data from the console.log does not show. I checked on Postman as well, and the request to the localhost URL just shows it grinding as "Sending Request".

const http = require("http");
const fs = require("fs");
const url = require("url");
const express = require("express");
const app = express();
app.use(
  express.urlencoded({
    extended: true,
  })
);


app.use(express.json());
const server = http.createServer((req, res) => {
  const { query, pathname } = url.parse(req.url, true);
  if (pathname == "/") {
    res.writeHead(200, { "Content-type": "text/html" });
    const outMap = Array.from(teams)
      .map((el) => homepageTeamLister(teamsListHTML, el))
      .join("");

    res.end(outMap);
  } else if (pathname == "/player") {
    //res.writeHead(200, { "Content-type": "text/html" });

    app.get("/test", function (req, res) {
      res.setHeader(
        "Access-Control-Allow-Origin",
        "http://localhost:9000/test"
      );
      res.setHeader("Access-Control-Allow-Methods", "GET");
      const myObj = { name: "John", age: 30 };
      res.send(myObj);
    });
  }
});

server.listen(9000, "127.0.0.1", () => {
  console.log("listening on port 9000");
});

And my HTML Script code:

console.log("Entered Script");
  fetch('/test')
    .then(res => res.json())
    .then(data => {
      console.log("Hi? : " , data); // { name: "John", age: 30 }
    })
    .catch(console.error);

    $.ajax({
  url: 'http://localhost:9000/test',
  complete: function(data) {
    console.log(data);
  }

I have tried both the fetch function, and used AJAX, but both attempts did not work.

答案1

得分: 0

以下是翻译好的部分:

"Express.js 和 HTML 的代码似乎没有正确设置。"

"您可以在此处预览最终代码。"

"将以下 HTML 代码放置到 public/index.html 文件中:"

<html>
<script src='https://code.jquery.com/jquery-3.6.4.min.js'></script>
<script>
  console.log("进入脚本");
  fetch("/test")
    .then(res => res.json())
    .then(data => {
      console.log("嗨?:", data); // { name: "John", age: 30 }
    })
    .catch(console.error);

  $.ajax({
    url: "https://xise6v-9000.csb.app/test",
    complete: function(data) {
      console.log(data?.responseText);
    }
  });
</script>
</html>

"请更新您的 app.js 文件以使其类似于以下代码。我已包含注释以提供更多上下文和理解:"

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

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

// 在 public 文件夹下提供 HTML 文件
app.use(express.static("public"));
app.use(express.json());

// 声明 API 的正确方式
app.get("/test", function(req, res) {
  res.setHeader(
    "Access-Control-Allow-Origin",
    "http://localhost:9000/test"
  );
  res.setHeader("Access-Control-Allow-Methods", "GET");
  const myObj = {name: "John", age: 30};
  res.send(myObj);
});

// 使用 app listen 替代
app.listen(9000, "127.0.0.1", () => {
  console.log("监听端口 9000");
});

"您可以通过访问此链接来预览结果。"

英文:

It appears that your code for Express.js and HTML was not set up correctly.

You can preview the final code here

place the HTML code below to public/index.html

&lt;html&gt;
&lt;script src=&#39;https://code.jquery.com/jquery-3.6.4.min.js&#39;&gt;&lt;/script&gt;
&lt;script&gt;
  console.log(&quot;Entered Script&quot;);
  fetch(&quot;/test&quot;)
    .then(res =&gt; res.json())
    .then(data =&gt; {
     console.log(&quot;Hi? : &quot;, data); // { name: &quot;John&quot;, age: 30 }
    })
    .catch(console.error);

  $.ajax({
    url: &quot;https://xise6v-9000.csb.app/test&quot;,
    complete: function(data) {
     console.log(data?.responseText);
    }
  });
&lt;/script&gt;
&lt;/html&gt;

update your app.js file to resemble the code below. I have included comments to provide more context and understanding:

const express = require(&quot;express&quot;);
const app = express();

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

// serve the html file under the public folder
app.use(express.static(&quot;public&quot;));
app.use(express.json());


// correct way to declare the API
app.get(&quot;/test&quot;, function(req, res) {
  res.setHeader(
    &quot;Access-Control-Allow-Origin&quot;,
    &quot;http://localhost:9000/test&quot;
  );
  res.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;GET&quot;);
  const myObj = {name: &quot;John&quot;, age: 30};
  res.send(myObj);
});

// use app listen instead
app.listen(9000, &quot;127.0.0.1&quot;, () =&gt; {
  console.log(&quot;listening on port 9000&quot;);
});

You can preview the result by following this link.

答案2

得分: -1

以下是翻译好的代码部分:

const http = require("http");
const fs = require("fs");
const url = require("url");
const express = require("express");
const app = express();
app.use(
  express.urlencoded({
    extended: true,
  })
);

app.use(express.json());
app.get("/test", function (req, res) {
  res.setHeader(
    "Access-Control-Allow-Origin",
    "http://localhost:9000/test"
  );
  res.setHeader("Access-Control-Allow-Methods", "GET");
  const myObj = { name: "John", age: 30 };
  res.send(myObj);
});

app.listen(9000, "127.0.0.1", () => {
  console.log("listening on port 9000");
});

请注意,我只提供了代码的翻译部分,没有其他内容。

英文:

try this pls:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const http = require(&quot;http&quot;);
const fs = require(&quot;fs&quot;);
const url = require(&quot;url&quot;);
const express = require(&quot;express&quot;);
const app = express();
app.use(
  express.urlencoded({
    extended: true,
  })
);

app.use(express.json());
app.get(&quot;/test&quot;, function (req, res) {
  res.setHeader(
    &quot;Access-Control-Allow-Origin&quot;,
    &quot;http://localhost:9000/test&quot;
  );
  res.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;GET&quot;);
  const myObj = { name: &quot;John&quot;, age: 30 };
  res.send(myObj);
});


app.listen(9000, &quot;127.0.0.1&quot;, () =&gt; {
  console.log(&quot;listening on port 9000&quot;);
});

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月6日 15:22:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定