How to use Ajax with express.js ? | Sololearn: Learn to code for FREE!

+1

How to use Ajax with express.js ?

7/4/2020 5:06:45 AM

Ankit Chaudhary

4 Answers

New Answer

+3

//incomplete question https://www.sololearn.com/discuss/229441/?ref=app https://www.sololearn.com/discuss/479093/?ref=app https://www.sololearn.com/discuss/1214800/?ref=app https://www.sololearn.com/discuss/1392587/?ref=app https://www.sololearn.com/discuss/949793/?ref=app

+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