Inside the route handler, use the method res.json() , passing in an object as an argument. This method closes the request-response loop, returning the data. Behind the scenes, it converts a valid JavaScript object into a string, then sets the appropriate headers to tell your browser that you are serving JSON, and sends the data back. A valid object has the usual structure {key: data} . data can be a number, a string, a nested object or an array. data can also be a variable or the result of a function call, in which case it will be evaluated before being converted into a string.
Hello,
Can anyone else help me with this problem? I cant get my code to pass, even though when i go to ‘my-app-url/json’ it displays '{“message”: “HELLO JSON”} as the exercise specifies. I’ve been at this for a few days, and have tried every method i can think of to display ‘{“message”: “HELLO JSON”}’. My .env file is also named just ‘.env’ in the root(under the views tab, where myApp.js is located, correct me if my understanding of the root is incorrect). Does anyone have any ideas I might not be thinking of? Here is my code at the moment:
require(‘dotenv’).config();
var express = require(‘express’);
var app = express();
app.get(’/’, function(req, res) {
//retrieve path of HTML file.
absolutePath = __dirname + ‘/views/index.html’ ;
res.sendFile(absolutePath);
});