I'm getting feed from this link. I want to get only first five items from feed. Instead of that I'm getting all of the items from feed. How can I get first five items only ?. Should I pass any parameters with URL ?
HTTP.get('https://buzz.machaao.com/feed',
(err, res) => {
if(err) {
console.log(err);
}
else {
console.log(res);
}
});
No that is not possible. What you can do though is to make a GET request to https://buzz.machaao.com/latest with Accept: application/json header. You can pass a count parameter to limit the posts.
Related
I want read sitemap.xml file and then want to check status of every url present in sitemap.
URL present in sitemap are around 20K so I dont want to visit url but just wants to check status and as url count is too large wants to run every url as one test case so that one of test case failure would not affect remaining ones.
Wants to implement above in Cypress
There is an answer here Cypress.io - sitemap.xml validation test that may start you off.
Instead of cy.visit(url) use cy.request(url), it should be much faster.
it('check each url in the sitemap.xml', () => {
const results = []
cy.request('sitemap.xml')
.then(response => {
// convert sitemap xml body to an array of urls
urls = Cypress.$(response.body)
.find('loc')
.toArray()
.map(el => el.innerText)
return urls
})
.then(urls => {
urls.forEach(url => {
cy.request({
url,
failOnStatusCode: false // get status good and bad
})
.then(response => {
results.push({url, statusCode: response.statusCode})
})
})
})
// use results inside .then()
cy.then(() => {
console.log(results)
})
})
BTW putting each URL in a separate test is a big headache.
The above pattern will give you status codes on good and bad URLS, and will be faster than separate tests.
I have a post page and a category page in my project as well as the usual internal pages.
Right now I have the following structure in the pages folder:
pages/category/_id.vue - I send a request for a category
pages/post/_id.vue - send request for post
pages/page/_id.vue - send request for page.
The api for the project is written in laravel (don't know if it matters).
I want nuxt to know which request to send, to fetch category or post, and then choose desired template to display category or post. If there is no category or post, then make redirect to the page 404. Is it possible?
The API provider doesn't matter in this case. Only the logic within Vue/Nuxt page template lifecycle.
Every page template so category / post / page with provided id can use different endpoint to fetch the data from API.
Which Nuxt? 2 or 3?
In Nuxt 2 You should use asyncData of specific page template ex: post:
async asyncData ({ store, $axios, params, error }) {
return $axios.get(`${apiEndpoint}/posts`, {
params: {
id: params.id
}
}).then(item => {
if (item.data.length === 0) throw({ statusCode: 404, message: 'Post not found' })
return { item: item.data[0] }
}).catch(e => {
error(e)
})
}
If You want to force 404:
try {
} catch (err) {
if (err.response.status === 404) {
return this.$nuxt.error({ statusCode: 404, message: err.message })
}
}
I have been trying to grab an old response to assert it has a certain response.
The issue is that the same call is posted at the same time and I can only grab the second response.
I was just wondering if there was a way to grab both responses so I can read each body to make sure the correct posts are made
I have used the following
public assertMixPanelCall(call: string): void {
cy.intercept('POST', 'https://api-js.mixpanel.com/track/*', (req) => {
if (atob(req.body.replace('data=', '')).includes(`"event": "${call}"`)) {
req.alias = 'correctBody'
}
});
cy.wait('#correctBody');
}
So the response I get is the last response,
But I want to grab the penultimate response
I'm not seeing the complete picture, but I think you can use this pattern Intercepting a response
let responseCount = 0;
cy.intercept('POST', 'https://api-js.mixpanel.com/track/*', (req) => {
if (atob(req.body.replace('data=', '')).includes(`"event": "${call}"`)) {
req.continue((res) => {
responseCount++;
if (responseCount === 1) {
req.alias = 'penultimate'
}
if (responseCount === 2) {
req.alias = 'final'
}
})
}
});
cy.wait('#penultimate')
Not sure if dynamic aliasing works on a per-response basis.
There's also an undocumented alias suffix that lets you access the nth response
cy.wait('#correctBody'); // must wait first
cy.get('#correctBody.1'); // then get to access response history
// - not sure if you need #correctBody.0 or #correctBody.1
But I can't see why cy.wait('#correctBody') doesn't catch the first response, generally you need to issue the wait twice to get both responses. Anyway, there's some things to try out here.
So I found the solution
From wherever I want to start capturing
cy.intercept('POST', 'https://api-js.mixpanel.com/track/*').as('call');
generate array based on the number of calls previously I wish to check
const genArr = Array.from({length:noOfCalls},(v,k)=>k+1);
const calls = [];
cy.wrap(genArr).each(() => {
calls.push(`#${call}`)
})
make the call based on the amount of times I wish to post the response
cy.wait(calls).then(differentRequests => {
differentRequests.forEach(differentRequest => {
if(atob(differentRequest.request.body.replace('data=','')).includes(call)) {
pass = true
}
});
expect(pass).to.be.true
});
}
Got the solution from here
https://medium.com/slido-dev-blog/cypress-io-is-pretty-amazing-and-if-you-havent-used-it-yet-and-need-a-jump-start-i-recommend-my-66ee6ac5f8d9
This time I want to use res.render to display html as success of DB update. I did it several times, but this time it doesn't work. It's not render html file, just displayed on chrome's console.
I think it caused because of async problem or duplicated response. I tried to many ways but I couldn't solve it, so pointers appreciated.
The code is related when the user paid service, increase user's level.
Get Access Token => Validate => res.render
app.post('/payment/validate', function(req, res, next){
// Get access token
request.post({
url : 'https://payment-company/get/token'
}, function(err, response, body) {
if(!err & response.statusCode == 200) {
var result = JSON.parse(body);
var accessToken = result.response.access_token;
// Validate payment (compare paid and would be paid)
request.get({
headers : { 'Authorization' : accessToken }
url : 'https://payment-company/find/paymentid'
}, function (err, response, body) {
if (!err && response.statusCode == 200){
var result = JSON.parse(body);
if (result.response.amount == req.body.price){
Members.findOne({id : req.user.id}, function(err, member){
// If no problem, update user level
member.level = 2;
member.save(function(err, result){
if (err) return next();
res.render('payment.view.result.ejs',
{
title : 'Success !',
description : 'level up.'
});
});
});
}
} else {
...
}
});
}
})
});
sorry to verbose code I tried to shorten code, No problem until res.render, res.render will work but it's not display page instead it just send html code to chrome's console.
Looks like there's a bit of a misunderstanding of how these requests work. What I think you intend:
Browser makes a GET request, server responds with an HTML document, the browser renders it
User takes an action
Browser makes a POST request, server responds with an HTML document, the browser renders it
What you've started coded on the frontend is an alternate method:
You make a POST request via AJAX, server responds with some JSON, you modify the current document with JavaScript to let the user know
Now I ran into a problem with managing ajax requests on nodeJS server. Currently I have this system it works, but it's ugly and not that efficient.
router.post('/get', function(req, res) {
var request = req.body.request;
if (request == null) {
res.json({success: 'false', error: 'Response returned null'});
return;
}
if (request == "render_page") {
var page = req.body.page;
if (page == null) {
res.json({success: 'false', error: 'Page returned null'});
return;
}
res.render(page);
} else if (request == "render_article") {
var temp = {
articles: [
{title: 'ABC', text: 'This is a test article'},
{title: 'XYZ', text: 'Just another random article'}
]
};
res.render('template/article-format', temp);
} else {
res.json({success: 'false', error: "Unknown request " + request});
}
Is there a better way to do this and even maybe make it dynamic? Also the server likes to crash if something goes wrong so there's that.
You seem to be fighting with the concepts of GET and POST. GET requests are supposed to be used for fetching things (like pages). Yet, you have specified a POST request, then named it /get, and then put the context in the request body.
If you simply leveraged some parameters in your GET requests, then you don't need to send a post with body (which I'm assuming you are using a POST request because you thought you needed to be able to send the request context data, in this case the page name).
So, you have a bunch of get requests that are being called as post requests. Really what you want is something like this:
router.get('/page/:page', function(req, res) {
var page = req.params.page;
// Logic here
});
And for handling the "null" page, you just route them to the /page url automatically (since if there is no parameter, it is just the /page url).
For further reading, I'd look over:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
http://expressjs.com/4x/api.html#req