let path=`api.openweathermap.org/data/2.5/weather?q=London`;
let apiKey= `&APPID=758bab291826491e79f93979de2ba255`
let url= path+apiKey;
function getWeather(url){
return fetch(url)
.then(response=> response.json())
.then(data=>console.log(data))
.catch(err=> console.log(err))
}
getWeather();
im getting this in the console
I cant figure it out, i'm very new to this. Its saying 404 but if I copy the URL and go to it it shows the JSON data
err after adding https://
this should do the trick:
let path = `https://api.openweathermap.org/data/2.5/weather?q=London`;
let apiKey = `&APPID=758bab291826491e79f93979de2ba255`;
let targetURL = path + apiKey;
function getWeather(url) {
return fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err));
}
getWeather(targetURL);
so there are 2 problems with your initial question:
when you do a fetch it tries to do the fetch from the domain the the
app is currently in. Which is why you're getting 127.0.0.1:5000
(localhost), if you supply https:// it should not do that.
you were not passing in the url to the getWeather(url) function that
you had declared. Hope this helps!
try this instead:
let path=`https://api.openweathermap.org/data/2.5/weather?q=London`;
let apiKey=`&APPID=758bab291826491e79f93979de2ba255`
let url=path+apiKey;
function getWeather(url){
return fetch(url)
.then(response=> response.json())
.then(data=>console.log(data))
.catch(err=> console.log(err))
}
getWeather();
This should work. why? Because when you do a fetch it tries to do the fetch from the domain the the app is currently in. Which is why you're getting 127.0.0.1:5000 (localhost), if you supply https:// it should not do that.
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.
FilePond.setOptions({
server: {
fetch: (url, load, error, progress, abort, headers) => {
fetch(url)
.then(res => res.blob())
.then(load);
}
I've found this configuration online. I cannot understand why this works. Should'nt this lead to a stack-overflow?
IMO the function is calling itself recursively or am i getting anything wrong?
In this example the first fetch is a property of server, the second fetch is the JavaScript native fetch function.
You could also write it like this, which maybe makes things a bit more clear?
function getData(url, load) {
return fetch(url)
.then(res => res.blob())
.then(load)
}
const options = {
server: {
fetch: getData
}
}
FilePond.setOptions(options);
I'm making a post request using Axios and this call returns data in the response headers and body. In the headers, it's returning an x-auth-token and I want to get the value of this token but it returns:
undefined is not an object
Here is how I'm doing it:
axios.post('app.com/api/login', data)
.then(response => {
console.log(response.headers.get("x-auth-token"));
})
.catch(error => {
console.log(error)
});
You need to parse your response first.
axios
.post('app.com/api/login', data)
.then(response => response.json())
.then(response => {
console.log(response.headers.get("x-auth-token"));
})
.catch(error => {
console.log(error)
});
After that, In second then you can log the whole response and find where your x-auth-token resides.
In the Github comment, it's clearly mentioned how to retrieve the headers
see
fetchFromServer = async(data) => {
const response = await axios.post(url, data, headers)
console.log(response.headers)
}
If you could see all the headers in your log you can try either of these to get the data from the response. To check the keys available in your response you can try
console.log(Object.keys(response.headers))
console.log(response.headers.your_required_key (For example response.headers.token)
console.log(response.headers["your_required_key"] if the above fails. (console.log(response.headers["content-type"])
I am wondering if it is possible to do in fetch all the things you can do in traditional ajax?
Because I'm having a problem with a simple login authentication using express. I want to send a response like Login error if the username/password is incorrect, or to redirect the user to the homepage if both is correct, to the client without refreshing the page.
I understand that you can do this in AJAX, but is it possible to do it in fetch also?
I tried using express js and sending a response through a json, but I can't figure out how to handle the response without refreshing the page.
I tried doing it like this in the express server
//if valid
res.json({
isValid: true
})
//if invalid
res.json({
isValid: false
})
And in the client side, specifically in the login page, I have this javascript that handles the submitting of the information
fetch('https://localhost:3000/auth', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username,
password
})
})
.then(response => response.json())
.then(data => {
//I understand that in this part, you can handle the response, but the problem is, I don't know how.
}
})
.catch(console.log)
You are SO close! You've got the fetch, then you've parsed it with response.json, so the next thing is the .then(). In that, you have the JSON object being passed into a param you've named data. All you need to do is check if that has the isValid property!
fetch('https://localhost:3000/auth', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username,
password
})
})
.then(response => response.json())
.then(data => {
if(data.isValid){
// Do something with a valid user. Redirect or whatever.
} else {
// Here, isValid is not set, or is false.
// Send them packing!
}
}
})
.catch(err => console.error("I died: ", err) );
ALSO, take a look at the .catch() block -- in the event of an error, that catches an Error thrown by either the fetch(), or a then(). So you need to add a parameter for the error, and a function body to handle that. I've edited my code sample to demonstrate.
Won't actually run here, but it's formatted all pretty.
When using two nested chai requests, session get lost.
chai.request(server)
.post('/api/v1/account/login')
.send({_email: 'test#test.com', _password: 'testtest'})
.end(function(err, res){
chai.request(server)
.get('/api/v1/user/me')
.end(function(err2, res2){
//here i should get the session, but its empty
res2.should.have.status(200);
done();
});
});
And i'm pretty sure that it's an error in my mocha test, because i tried it (the login and then retrieving the session) outside the test and the session is being setted.
express itself does not have any native session support. I guess you are using some session middleware such as https://github.com/expressjs/session.
Meanwhile, I guess you are using chai-http plugin to send HTTP request. In chai-http, in order to retain cookies between different HTTP requests (so that req.session can be available in express side), you need to use chai.request.agent rather than chai.
Here is a simple example for your code:
var agent = chai.request.agent(app);
agent.post('/api/v1/account/login')
.send({_email: 'test#test.com', _password: 'testtest'})
.then(function(res){
agent.get('/api/v1/user/me')
.then(function(res2){
// should get status 200, which indicates req.session existence.
res2.should.have.status(200);
done();
});
});
For chai.request.agent, you can refer to http://chaijs.com/plugins/chai-http/#retaining-cookies-with-each-request
In case anyone else comes across this issue, this approach worked for me using Mocha:
it("should...", () => {
return agent.post('/api/v1/account/login')
.send({_email: 'test#test.com', _password: 'testtest'})
.then(async res => {
const res2 = await agent.get('/api/v1/user/me')
res2.should.have.status(200);
})
.catch(error => {
throw error;
});
});