+ 1
How to use Ajax with express.js ?
Ajax tutorial
4 Antworten
+ 1
const fetch = require("node-fetch")
const url = "https://jsonplaceholder.typicode.com/users"
fetch(url)
.then(res => res.json)
.then(data => console.log(data))
.catch(err => console.log(err)
0
Setup express.js with ejs and node-fetch
// 1) In server.js
const express = require("express");
const app = express();
const fetch = require('node-fetch');
app.set("port", process.env.PORT || 3000);
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.get("/", (req, res) => {
let usersData = [];
const url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then(res => res.json())
.then(json => {
usersData = json;
res.render("index", {users: usersData});
console.log(json);
}).catch((e) => {
console.error(e.message);
});
});
// listen for requests :)
app.listen(app.get("port"), () => {
console.log("Your app is listening on port " + app.get("port"));
});
0
// 2) in views/index.js
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link href="/style.css" rel="stylesheet">
</head>
<body>
<h1>Main page</h1>
<ul>
<% users.forEach(function(user){ %>
<li><%= user.name %> (<%= user.email %>)</li>
<% }); %>
</ul>
<script src="/script.js"></script>
</body>
</html>
To run this code from Code Playground with Glitch iframe
https://code.sololearn.com/WGl1YnkhI2Tn/?ref=app