I'm using this code and when running from cmd, the code works but my localhost server won't respond. When I change all of the https to http then my localhost server responds but can't display the data of the fork2fork server because they now use https. It says 301 moved permanently.
My code is:
const https = require('https')
let url = require('url')
let qstring = require('querystring')
let ingredient
const PORT = process.env.PORT || 3000
//Please register for your own key replace this with your own.
const API_KEY = 'f1a2e758886bb058454608e53ab3039a' //<== INSERT YOUR KEY HERE
function sendResponse(recipeData, res) {
var page = '<html><head><title>API Example</title></head>' +
'<body>' +
'<form method="post">' +
'Ingredient: <input name="ingredient"><br>' +
'<input type="submit" value="Get recipes">' +
'</form>'
if (recipeData) {
page += '<h1>Recipes</h1><p>'+ recipeData + '</p>' //ADDED Recipe!
}
page += '</body></html>'
res.end(page);
}
function parseData(recipeResponse, res) {
let recipeData = ''
recipeResponse.on('data', function(chunk) {
recipeData += chunk
})
recipeResponse.on('end', function() {
sendResponse(recipeData, res)
})
}
function getRecipes(ingredient, res) {
//Many API services now require that clients register for an app id.
const options = {
host: 'www.food2fork.com',
path: `/api/search?q=${ingredient}&key=${API_KEY}`
}
//console.log(options.path);
https.request(options, function(apiResponse) {
parseData(apiResponse, res)
}).end()
}
https.createServer(function(req, res) {
let requestURL = req.url
let query = url.parse(requestURL).query //GET method query parameters if any
let method = req.method
console.log(`${method}: ${requestURL}`)
console.log(`query: ${query}`) //GET method query parameters if any
if(req.method == "GET") {
ingredient = (qstring.parse(query)).ingredient;
getRecipes(ingredient,res);
} //ADDED GET REQUEST CODE
// if (req.method == "POST") {
else if (req.method == "POST") {
let reqData = ''
req.on('data', function(chunk) {
reqData += chunk
})
req.on('end', function() {
console.log(reqData);
var queryParams = qstring.parse(reqData)
console.log(queryParams)
getRecipes(queryParams.ingredient, res)
})
} else {
sendResponse(null, res)
}
}).listen(PORT, (error) => {
if (error)
return console.log(error)
console.log(`Server is listening on PORT ${PORT} CNTL-C to quit`)
})
What should I change in this code so that I can access the fork2fork server that uses https and that my server responds when I run my script using https?
Aucun commentaire:
Enregistrer un commentaire