I am trying to create a search function that auto populates my form with the corresponding record from my database and get API.
Here is my route
//Get number and dets to page
router.get("/sop/:id", function (request, response, next) {
response.render("test", { output: request.params.id });
});
//Elements i want to print my results to
const sopN = document.getElementById("sop");
const CustName = document.getElementById("cusName");
const button = document.getElementById("subBtn");
button.onclick = function (e) {
e.preventDefault();
const url = "http://localhost:6600/api/sopId/";
let sopSearch = document.getElementById("sop");
fetch(`${url}/${sopSearch.value}`, {
method: "GET",
})
.then((response) => response.json())
.then((json) => console.log(json));
};
The error says I'm getting is:
"http://localhost:6600/api/sopId/(record)" 404 not found and uncaught in promise Syntax error: unexpected token < in JSON at position 0
Please any and all assistance will be is appreciated
There's a problem with your URL.
Your route is "/sop/:id", so something like "http://localhost:6600/api/sop/1", but your URL is "http://localhost:6600/api/sopId/" to which you're appending sopSearch.value turning it into "http://localhost:6600/api/sopId/1".
So change this const url = "http://localhost:6600/api/sopId/"; to const url = "http://localhost:6600/api/sop/";
Related
I created an Azure Machine Learning model with a REST Endpoint as a way to consume it. When I run the service using Postman everything seems to work fine.
However, when I try to create an HTML website (Codepen) with a javascript to call the REST Endpoint I only get an Error: Failed to Fetch message.
I also tried with Azure Static Web Apps and I am unsuccessful as well.
I was however able to verify (in the Console) that my input to the Rest Endpoint via Codepen is the same as Postman.
Is there anything I am missing out here?
Here is a sample of my javascript:
<script>
const form = document.querySelector('#agriculture-form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const areaHarvest = parseFloat(document.querySelector('#area-harvest').value);
const farmGatePrice = parseFloat(document.querySelector('#farm-gate-price').value);
const volumeOfImport = parseFloat(document.querySelector('#volume-of-import').value);
const lowTemp = parseFloat(document.querySelector('#low-temp').value);
const averageTemp = parseFloat(document.querySelector('#average-temp').value);
const highTemp = parseFloat(document.querySelector('#high-temp').value);
const precipitationMm = parseFloat(document.querySelector('#precipitation-mm').value);
const precipitationDays = parseFloat(document.querySelector('#precipitation-days').value);
const tropicalCyclones = parseFloat(document.querySelector('#tropical-cyclones').value);
const volumeProductionGuess = 0;
const data = {
"Area_Harvested": areaHarvest,
"FarmGatePricePHPPSA": farmGatePrice,
"Volume_of_Import": volumeOfImport,
"temp_low": lowTemp,
"temp_ave": averageTemp,
"temp_high": highTemp,
"precipitation_mm": precipitationMm,
"precipitation_days": precipitationDays,
"tropical_cyclone": tropicalCyclones,
"Volume_of_Production": volumeProductionGuess
};
const formattedData = [data];
console.log('formatted data:', formattedData);
const testData = JSON.stringify(formattedData);
console.log('test data:', testData);
document.getElementById("demo").innerHTML = testData;
fetch('http://ziggyapimanagementservice.azure-api.net/score', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'cd529cc993494fdfb1530eaf04ae63dc'
},
body: testData
})
.then(response => response.json())
.then(data => {
console.log(data);
const result = data.result[0]; // Get the result array from the response
const volumeForecastElement = document.querySelector('#volume-forecast');
volumeForecastElement.textContent = result.join(', '); // Update the text content of the <b> element with the result array joined by commas
document.getElementById("result").innerHTML = result;
})
.catch(error => {
document.getElementById("error").innerHTML = error.message;
console.error(error.message)
});
});
And here is what I get in Postman:
As an exercise, I'm creating a simple API that allows users to provide a search term to retrieve links to appropriate news articles across a collection of resources. The relevent function and the route handler that uses the function is as follows:
function GetArticles(searchTerm) {
const articles = [];
//Loop through each resource
resources.forEach(async resource => {
const result = await axios.get(resource.address);
const html = result.data;
//Use Cheerio: load the html document and create Cheerio selector/API
const $ = cheerio.load(html);
//Filter html to retrieve appropriate links
$(`a:contains(${searchTerm})`, html).each((i, el) => {
const title = $(el).text();
let url = $(el).attr('href');
articles.push(
{
title: title,
url: url,
source: resource.name
}
);
})
})
return articles; //Empty array is returned
}
And the route handler that uses the function:
app.get('/news/:searchTerm', async (req, res) => {
const searchTerm = req.params.searchTerm;
const articles = await GetArticles(searchTerm);
res.json(articles);
})
The problem I'm getting is that the returned "articles" array is empty. However, if I'm not "looping over each resource" as commented in the beginning of GetArticles, but instead perform the main logic on just a single "resource", "articles" is returned with the requested data and is not empty. In other words, if the function is the following:
async function GetArticles(searchTerm) {
const articles = [];
const result = await axios.get(resources[0].address);
const html = result.data;
const $ = cheerio.load(html);
$(`a:contains(${searchTerm})`, html).each((i, el) => {
const title = $(el).text();
let url = $(el).attr('href');
articles.push(
{
title: title,
url: url,
source: resources[0].name
}
);
})
return articles; //Populated array
}
Then "articles" is not empty, as intended.
I'm sure this has to do with how I'm dealing with the asynchronous nature of the code. I've tried refreshing my knowledge of asynchronous programming in JS but I still can't quite fix the function. Clearly, the "articles" array is being returned before it's populated, but how?
Could someone please help explain why my GetArticles function works with a single "resource" but not when looping over an array of "resources"?
Try this
function GetArticles(searchTerm) {
return Promise.all(resources.map(resource => axios.get(resource.address))
.then(responses => responses.flatMap(result => {
const html = result.data;
//Use Cheerio: load the html document and create Cheerio selector/API
const $ = cheerio.load(html);
let articles = []
//Filter html to retrieve appropriate links
$(`a:contains(${searchTerm})`, html).each((i, el) => {
const title = $(el).text();
let url = $(el).attr('href');
articles.push(
{
title: title,
url: url,
source: resource.name
}
);
})
return articles;
}))
}
The problem in your implementation was here
resources.forEach(async resource...
You have defined your function async but when result.foreach get executed and launch your async functions it doesn't wait.
So your array will always be empty.
I'm trying to make a fandom search command which is supposed to search the among us fandom wiki
but it isn't working at all telling that it isn't find any results
//formats to fit the proper url
const fetch = require('node-fetch')
const Parse = require('parse')
const url = require('url')
var term = args.join().replace(/,/g, "_")
term = term.toLowerCase()
//creates the api url being used
var apiurl = 'https://among-us.fandom.com//api/v1/Search/List?query=' + term + '&limit=1'
fetch(apiurl)
//converts response into a json format
.then(response => response.json())
//sends the proper url into the chat
.then(data => {
const page = data.items[0].id
var pageurl = 'https://among-us.fandom.com//api/v1/Articles/AsSimpleJson?id=' + page
fetch(pageurl)
.then(response => response.json())
.then(data => {
var test = data.sections[0].images.src
console.log(test)
const prev = page.snippet.replace(/\//g, '')
const embededSearch = new Discord.MessageEmbed()
.setTitle(page.title)
.setColor('#ffd000')
.setURL(page.url)
.setImage(test)
.addFields(
{ name: '\u200b', value: prev.replace(/<span>|<span class=\"searchmatch\">|'<'|'>'/g, '') + '...' }
)
message.channel.send(embededSearch)
})
})
//for when a page isn't found
.catch(function (e) {
message.channel.send('No results found')
});
i tried console logging the error and i get error TypeError: Cannot read property '0' of undefined could i get any help i have been trying for hours to make it work
I try to create some API to external adobe stock.
Like in the title, first time i get query from Link router of undefined, but after reload page it work correctly. My
main page
<Link
href={{
pathname: "/kategoria-zdjec",
query: images.zdjecia_kategoria
}}
as={`/kategoria-zdjec?temat=${images.zdjecia_kategoria}`}
className={classes.button}>
</Link>
and my server
app
.prepare()
.then(() => {
server.get("/kategoria-zdjec", async (req, res) => {
const temat = await req.query.temat;
console.log(temat)
const url = `https://stock.adobe.io/Rest/Media/1/Search/Files?locale=pl_PL&search_parameters[words]=${temat}&search_parameters[limit]=24&search_parameters[offset]=1`;
try {
const fetchData = await fetch(url, {
headers: { ... }
});
const objectAdobeStock = await fetchData.json();
res.json(objectAdobeStock);
const totalObj = await objectAdobeStock.nb_results;
const adobeImages = await objectAdobeStock.files;
} catch (error) {
console.log(error);
}
});
and that looks like getInitialProps on page next page
Zdjecia.getInitialProps = async ({req}) => {
const res = await fetch("/kategoria-zdjec");
const json = await res.json();
return { total: json.nb_results, images: json.files };
}
I think it is problem due asynchronous.
I think this might be due to the fact that you are using fetch which is actually part of the Web API and this action fails when executed on server.
You could either use isomorphic-fetch which keeps fetch API consistent between client and server, or use node-fetch when fetch is called on the server:
Zdjecia.getInitialProps = async ({ req, isServer }) => {
const fetch = isServer ? require('node-fetch') : window.fetch;
const res = await fetch("/kategoria-zdjec");
const json = await res.json();
return { total: json.nb_results, images: json.files };
}
This problem is solved, the issue was in another part of my app, directly in state management, just created new variables, and pass to link state value.
I am new to node js. I am trying to do scraping some value and name from the select tab from a particular website. My code as follows,
const rp = require('request-promise');
const crio = require('cheerio');
const url = 'https://myurl';
const getOptions = function(optionName,ignoreOption) {
return rp(url)
.then(function(html) {
crio('[name='+optionName+']', html).find('option').each((i,op) => {
if(crio(op).text() != ignoreOption && crio(op).text() != '')
return {
name: crio(op).text(),
value: crio(op).val(),
};
})
})
.catch(function(err) {
//handle error
});
};
getOptions('test','-- Select company name --')
.then( data =>
console.log(data)
);
When I try to run this code, I am getting result as 'undefined'. How do I get the return json response from the getOptions function here?
You are not returning a value inside your then function that is using crio.
Change
crio('[name='+optionName+']', html).find('option').each((i,op) => {
to
return crio('[name='+optionName+']', html).find('option').map((i,op) => {
Note the use of map instead of each.