I get confused on how to show json result I've got from api on my webpage
I am using express.js + node.js, and Bing API
here is my code
const https = require('https');
const express = require("express");
const app = express();
var port = 8000;
const SUBSCRIPTION_KEY = 'xxxxxxxxxxxxxxxxxxxxx'
if (!SUBSCRIPTION_KEY) {
throw new Error('error no keys')
}
app.use(express.static("example.com"));
function bingWebSearch(query) {
https.get({
hostname: 'api.cognitive.microsoft.com',
path: '/bing/v7.0/search?q=' + encodeURIComponent(query),
headers: { 'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY },
}, res => {
let body = ''
res.on('data', part => body += part)
res.on('end', () => {
// yes this could work and print out result json at my terminal
console.dir(JSON.parse(body), { colors: false, depth: null })
// but why this can not work with error msg I posted below
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ a: 1 }));
// I cant even output this on my webpage, and actually I want to print of course the result json
})
res.on('error', e => {
console.log('Error: ' + e.message)
throw e
})
})
}
app.get("/api", (req, res) => {
const searchString = `${req.query.q}`;
bingWebSearch(searchString);
});
app.listen(port, () => console.log('Your app is ready! Navigate to: http://localhost:' + port + '/.'));
and error msg here
/var/www/bing-web-search.js:27
res.setHeader('Content-Type', 'application/json');
^
/var/www/bing-web-search.js:28
res.end(JSON.stringify({ a: 1 }));
^
TypeError: res.setHeader is not a function
TypeError: res.end is not a function
at IncomingMessage.res.on (/var/www/bing-web-search.js:31:11)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
p.s. if I move line 27,28 into app.get
app.get("/api", (req, res) => {
const searchString = `${req.query.q}`;
bingWebSearch(searchString);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ a: 1 }));
});
They worked fine to appear on my webpage
So I just don't know how to make my result also shown on my webpage
Any tip or help would be appreciate, thank you!