I have an API link where I need to check the price of certain items. For example, Only change in the fetch url is the items. is there any easy way to do it in one fetch or using any loop
www.apirequest/item1/ps2
www.apirequest/item2/ps2
www.apirequest/item3/ps2
www.apirequest/item4/ps2
www.apirequest/item5/ps2
You need to pass the item name/id in body or you can also grap that from params. Then in the api point you can use fetch or axios to make api request.
const axios = require("axios");
app.post("/api/test", async (req, res) => {
const { param } = req.body // you can use query params
await axios.get(`www.apirequest/item1/${param}`).then((result)=>{
console.log(result)
})
res.send("okay");
});
Related
I want to update an attribute within a JSON object using fetch PUT. I've created a put function taking in 2 URL parameters
app.put('/trustRoutes/:id/:item', (req, res){
I am able to update the data with a single parameter but since I only want to change one value inside that object, calling put will replace the whole object with my new body.
below is what I've tried.
app.put('/trustRoutes/:id/:item', (req, res) => {
readFile(data => {
const userId = req.params['id/item'];
// have also tried const userId = req.params.id.item
data[userId] = req.body;
//write data back to file
I looked around at other examples but couldn't find any that were updating data instead of GET. If there is one I missed please let me know.
PUT requests are great for completely overwriting a resource, and is idempotent. This answer does a good job explaining idempotency. For updating a resource partially, a PATCH request is a better choice.
app.patch('/trustRoutes/:id/:item', (req, res) => {
readFile(data => {
data[userId] = req.params[id];
data[item] = req.params[item];
// A get request for this resource would now show both of the updated values
// Write file
I'm trying to pass data (array) from node.js backend to frontend JS to process it there. I don't want to pass data directly to backend-served html file because I'd like to keep it clean and don't want to do any loops there etc.
My backend part looks like this:
app.get("/search-db", function (req, res) {
const term = req.query.term;
findInDb(term);
res.redirect('/search', {
searchResults: searchResults,
});
})
async function findInDb(query) {
const collection = await getDbCollection();
await collection.find().forEach((item) => {
console.log(item.artist);
if (item.artist.includes(query) || item.name.includes(query)) {
searchResults.push(item);
}
})
}
Is this possible or do I have to clutter my html and use loop there to process passed results?
Your web page can use AJAX via fetch to make the /search-db API request to your server. Your server route handler should fetch the results from the DB, then invoke res.send() to send a JSON response back to the client, rather than res.redirect() to redirect the client to a new page.
Example: How to create a REST API with Express.js in Node.js
Also, unrelated, your findInDb function should return the search results instead of placing them in a global variable (searchResults).
I have a GET request that gets form data, then I need to trigger a second GET request on a different route that gives the form data to a REST API. I can do this manually through Postman, but I'd like the first GET request to trigger the second.
This is the idea:
app.get('form', (req,res,next) => {
//Get form data
//Pass form data
//Trigger next request
})
app.get('API', (req,res,next) => {
//Get data from previous request
//Use data in params
})
I would really appreciate any feedback! So far I've found posts talking about app._router.handle, but haven't been able to implement it correctly.
to pass data between middleware, you must assign it to request object like :
app.get('form', (req,res,next) => {
const { user, tags } = req.body
// assign this
req.data = { user, tags }
// pass to next
next()
})
app.get('API', (req,res,next) => {
// get the passed data
req.data
console.log(req.data)
})
I am sending an Axios request to a web page for scraping a little string off of it, but the returned response is a large html, and I only need a little part of it, is there a way to somehow shorten the response so I can save data and make the request faster?
const longHtml = await axios.get('https://example.com');
const shortHtml = longHtml.data //get short data here
If I understand what your trying to do, you wan't to stop the request when you find the data you want, you could use htmlparser2 and feed it a stream from axios and then register listeners and when you get the element you need you can end the stream.
Web scraping is a technique used for retrieving data from websites. You fetch the page's contents, and after that extract the data you need from the page.
here an example by using axios and cheerio
const axios = require("axios")
const cheerio = require("cheerio")
async function fetchHTML(url) {
const { data } = await axios.get(url)
return cheerio.load(data)
}
const $ = await fetchHTML("https://example.com")
// Print the full HTML
console.log(`Site HTML: ${$.html()}\n\n`)
// Print some specific page content
console.log(`First h1 tag: ${$('h1').text()}`)
I need to do some DOM manipulation based on some AJAX call. But I end up with the res.send on my page and I am unable to get the console.log I need to see the datas and be able to check what I need to insert in my Dom. All I see is the res.render and the JSON datas.
Even by trying to do some basic DOM creation it didnt work.
I manage to do some AJAX call already. Some Axios post, patch or delete, but I never needed to call the data when rendering the page, always through a button inside the page.
There must be something I am not understanding...
Router.get("/collection", async (req, res) => {
const dbRes = await Promise.all([
sneakerModel.find().populate("tag"),
tagModel.find()
]);
const sneakRes = dbRes[0];
const tagRes = dbRes[1];
res.send(tagRes);
});
// ===============================
// CLIENT SIDE =>
const allCollecRoutes = document.getElementById("allCollec");
allCollecRoutes.onclick = async () => {
const dbRes = await axios.get("http://localhost:9876/collection");
console.log(dbRes);
};
You appear to be expecting a JSON serialised response at the client but are sending a plain/text from the server i.e. res.send(tagRes)
Use res.json(tagRes) instead.