-
Notifications
You must be signed in to change notification settings - Fork 0
Survey Exercise
For this exersize we had to clean our own survey data. This data was collected at the start of the course, and was stored in a CSV file. This CSV file was cleaned and parsed into a JSON file by Jonah, Thanks for sharing!
In my first attempt to log the data to the console, I tried to open the local folder in the browser and used the fetch() API method.
fetch('../data/survey_id.json')
.then((response) => {
return response.json();
})
.then((obj) => {
console.log(obj);
})
.catch((error) => {
console.error('nope');
});This is the result i got from the console:
Cross origin requests are only supported for HTTP.
___
[Error] Fetch API cannot load [filepath] due to access control checks.
To fix this error I used the package live-server.
For easy use I've added live-server to my start script.
The server will start by running the command: $ npm start in the terminal.
The JSON data is now logged to the console.
For better readability of the code i rewrote the code adding some callbacks
const data = '../data/survey_id.json';
getData = (data) => {
fetch(data)
.then(status)
.then(json)
.then((data) => {
console.log('Request succeeded with JSON response', data);
})
.catch((error) => {
console.error('nope' + error);
});
};
getData(data);Get the response status
status = (response) => {
if (response.status >= 200 && response.status < 300) {
console.log(response);
return Promise.resolve(response);
} else {
return Promise.reject(new Error(response.statusText));
}
};Read the JSON response
json = (response) => {
return response.json();
};I've rewrote some functions to improve reusability.
And changed function names to match the functionality.
const data = '../data/Survey_Information_Design_clean-parsed.json';
fetchJSON = (data) => {
fetch(data)
.then(responseStatus)
.then(readResponseJSON)
.then(logResult)
.catch((error) => {
console.error('nope' + error);
});
}Get Response Status
responseStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
console.log(response)
return Promise.resolve(response);
} else {
return Promise.reject(new Error(response.statusText));
}
}Read the response
readResponseJSON = (response) => {
return response.json();
}log the results to the console.
logResult = (result) => {
console.log(result)
}Request succeeded with JSON response `Objects`