英文:
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
<html>
<script src='https://code.jquery.com/jquery-3.6.4.min.js'></script>
<script>
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: "https://xise6v-9000.csb.app/test",
complete: function(data) {
console.log(data?.responseText);
}
});
</script>
</html>
update your app.js file to resemble the code below. I have included comments to provide more context and understanding:
const express = require("express");
const app = express();
app.use(
express.urlencoded({
extended: true
})
);
// serve the html file under the public folder
app.use(express.static("public"));
app.use(express.json());
// correct way to declare the 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);
});
// use app listen instead
app.listen(9000, "127.0.0.1", () => {
console.log("listening on port 9000");
});
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("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");
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论