400 "Bad Request" error when using Thunder Client (Postman) API - javascript

I am using the Thunder Client app for VS code to use an API to save the user's data. The API is okay but there is something wrong with my code because I keep getting a 400 "Bad Request" error when I try to send the data to the API. I think the problem might be an array in my code and that is not being sent correctly.
const form = document.querySelector('.form');
const refresh = document.querySelector('.refresh-button');
export const scores = [];
renderScores();
// event listener
form.addEventListener('submit', (e) => {
e.preventDefault();
saveScore();
renderScores();
});
refresh.addEventListener('click', (e) => {
e.preventDefault();
getScores();
renderScores();
});
function renderScores() {
const scoreList = document.querySelector('.result-list');
scoreList.innerHTML = '';
scores.forEach((score) => {
const li = document.createElement('li');
li.innerHTML = `${score.user} : ${score.score}`;
scoreList.appendChild(li);
});
}
async function getScores() {
const savedScores = 'https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/Zl4d7IVkemOTTVg2fUdz/scores/';
const recievedScores = await fetch(savedScores);
const api = await recievedScores.json();
const scores = api.result;
renderScores(scores);
}
async function saveScore() {
const user = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
const newScore = {
user,
score,
};
scores.push(user, score);
await fetch('https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/Zl4d7IVkemOTTVg2fUdz/scores/', {
method: 'POST',
body: JSON.stringify({
newScore
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
getScores();
}
Hey guys I changed my code a little and now I am not getting an error but when I refresh my page I lose all the data

Related

The fetch code in onNewScanResult is executed more than once once a QR code has been scanned, and also updating database. How to stop it from running?

executing the fetch code in onNewScanResult multiplt time and hence updating the database accordingly................
initialization of qr scanner.........
this.html5QrcodeScanner = new Html5QrcodeScanner(
qrcodeRegionId,
config,
verbose
); ```Executing scanner when qrcode is scanned```
this.html5QrcodeScanner.render(
this.props.qrCodeSuccessCallback,
this.props.qrCodeErrorCallback
);
}
}
this is main qr code class........
class QrCode extends React.Component {
constructor() {
super();
this.state = {
decodedResults: [],
};
this.onNewScanResult = this.onNewScanResult.bind(this);
}
this is where the executing multiple time is happing.......
onNewScanResult(decodedText, decodedResult) {
`geting data from loacal storage as we saved data earlier in the process about acess level`
const qrRes = decodedText;
const obj = JSON.parse(qrRes);
const token = localStorage.getItem("user");
const userData = JSON.parse(token);
const username = userData[0].userId;
const accesslevel = userData[0].accessLevel;
const result = JSON.parse(qrRes);
const ele = result.ele_name;
const newdata = { ele, username, accesslevel };
const data = {
Element_detail: obj,
accessLevel: newdata.accesslevel,
};
const verifyUser = localStorage.getItem("accessLeveldetails");
const accessdetail = JSON.parse(verifyUser);
```checking is user is verified or not```......
`checking the acess level you can ignore the checking focus on fetch part`....
This particular part is we have to stop executing multiple time so database is only entered with one value
if (accessdetail.accessLevel === data.accessLevel) {
try { ``` this fetch is updating database with multiple entries```
fetch(
data.accessLevel === 20
? `/v0/all_elements_image`
: `/v0/${accessdetail.msg}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(obj),
}
).then((res) => {
console.log(res);
if (!res) {
throw res;
}
return res.json();
});
} catch (error) {
console.log("Error:", error);
}
} else {
alert("WRONG USER");
}
}
}

getting this error in my code, Failed to fetch at sendData (form.js:42:5)

Screenshot of error:
So, basically i'm getting this weird error in my java Script file, called: Failed to fetch
at sendData
and i don't know quite what is the error, i cant save nothing to my database cause of this error
here's the code from the form.js :
const loader = document.querySelector('.loader');
// select inputs
const SubmitBtn = document.querySelector('.submit-btn');
const name = document.querySelector('#name');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const number = document.querySelector('#number');
const tac = document.querySelector('#terms-and-cond');
const notification = document.querySelector('#notification');
SubmitBtn.addEventListener('click', () => {
if (name.value.length < 3) {
showAlert('name must be 3 letters long');
} else if (!email.value.length) {
showAlert('enter your email');
} else if (password.value.length < 8) {
showAlert('password should be 8 letters long');
} else if (!number.value.length) {
showAlert('enter your phone number');
} else if (!Number(number.value) || number.value.length < 10) {
showAlert('invalid number, please enter a valid one');
} else if (!tac.checked) {
showAlert('you must agree to our terms and conditions')
} else {
// submeter o form
loader.style.display = 'block';
sendData('/signup', {
name: name.value,
email: email.value,
password: password.value,
number: number.value,
tac: tac.checked,
notification: notification.checked,
seller: false
})
}
})
// send data function
const sendData = (path, data) => {
fetch(path, {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data)
}).then((res) => res.json())
.then(response => {
processData(response);
})
}
const processData = (data) => {
loader.style.display = null;
if (data.alert) {
showAlert(data.alert);
}
}
// alert funcionalidade
const showAlert = (msg) => {
let alertBox = document.querySelector('.alert-box');
let alertMsg = document.querySelector('.alert-msg');
alertMsg.innerHTML = msg;
alertBox.classList.add('show');
setTimeout(() => {
alertBox.classList.remove('show');
}, 3000);
}
with this i always get the same error, it doesn't save the users to the database, and its kinda irritating. i would like help for this type of error as soon as possible. this for a school project and time is coming short...

how to call api recursively until nested stack keys are finished

here is my question how to call api recursively untill nested data stack keys are finished
here is my full explaination in image
i found this relatable code for recursion api call at this post recursive api call
function callFW() {
d3.json(url, async function(data) {
Tree["uid"] = data.request.uid
Tree["hid"] = data.firmware.meta_data.hid
Tree["size"] = data.firmware.meta_data.size
Tree["children"] = [];
await BuildTree(data.firmware.meta_data.included_files,Tree["children"]);
console.log(Tree)
})
}
async function BuildTree(included_files, fatherNode) {
if (included_files.length > 0) {
let promises = included_files.map( item => {
let url = endpoint + "file_object/" + item + "?summary=true";
return axios.get(url)
});
const results = await Promise.all(promises);
for(let response of results){
var node = {}
node["uid"] = response.data.request.uid
node["hid"] = response.data.file_object.meta_data.hid
node["size"] = response.data.file_object.meta_data.size
node["children"] = []
fatherNode.push(node)
await BuildTree(response.data.file_object.meta_data.included_files, node["children"]);
};
}
};
this is im using custom useRecurseFetch for getting post api result
but i have no idea how to change this code for recursive api call
import React from 'react';
import qs from 'qs';
import axios from 'axios';
const useRecurseFetch = query => {
const [status, setStatus] = React.useState('idle');
const [result, setResult] = React.useState([]);
const [findClass, setFindClass] = React.useState([]);
// console.log(passVariable);
var data;
data = qs.stringify({
query: `http://www.blabla{ ${query}/category}`,
});
// eslint-disable-next-line no-undef
var Grant = process.env.REACT_APP_GRANT;
// eslint-disable-next-line no-undef
var Client = process.env.REACT_APP_CLIENT;
// eslint-disable-next-line no-undef
var Key = process.env.REACT_APP_KEY;
// eslint-disable-next-line no-undef
var Auth = process.env.REACT_APP_AUTH;
// eslint-disable-next-line no-undef
var Query = process.env.REACT_APP_QUERY;
const queryCall = React.useCallback(
async token => {
if (!token) {
return;
} else {
setStatus('Loading');
var config = {
method: 'POST',
url: `${Query}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
token.data.token_type + ' ' + token.data.access_token,
},
data: data,
};
axios(config)
.then(response => {
setResult(response.data.results.bindings);
let originalResult = response.data.results.bindings
.filter(ek => ek.class !== undefined && ek)
.map(el => el.obj.value);
setFindClass(originalResult);
setStatus('success');
})
.catch(function (error) {
setStatus('error');
});
}
},
[data]
);
React.useEffect(() => {
const authInitiate = () => {
var data = qs.stringify({
grant_type: `${Grant}`,
client_id: `${Client}`,
client_secret: `${Key}`,
});
var config = {
method: 'POST',
url: `${Auth}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then(response => {
queryCall(response);
})
.catch(function (error) {
console.log(error);
});
};
authInitiate();
}, [queryCall]);
return [status, result, findClass];
};
export default useRecurseFetch;
please any one can help me out with this code, im unable to figure out whats going in this code
anyhelp is really saved my day and really so appreciatable
here i called useRecurseFetch custom function in app.js
const [loadingStatus, mainData, addDataToPostItemArray] = useRecurseFetch(
`<kk:cat>`
);
please any one can help me out please im stuck with this process of calling api

How can I integrate SvelteKit and Google Forms?

SvelteKit's breaking change of Jan 19 (see here for details) means that my Google Forms integration is no longer working.
It was a minor struggle to get it working in the first place, and I can't bring this up to date — I repeatedly get the error message, "To access the request body use the text/json/arrayBuffer/formData methods, e.g. body = await request.json()", and a link to the GitHub conversation.
Here's my Contact component...
<script>
let submitStatus;
const submitForm = async (data) => {
submitStatus = 'submitting';
const formData = new FormData(data.currentTarget);
const res = await fetch('contact.json', {
method: 'POST',
body: formData
});
const { message } = await res.json();
submitStatus = message;
};
const refreshForm = () => {
/* Trigger re-render of component */
submitStatus = undefined;
};
</script>
... and here's the corresponding contact.json.js:
export const post = async (request) => {
const name = request.body.get('name');
const email = request.body.get('email');
const message = request.body.get('message');
const res = await fetch(`URL TO RELEVANT GOOGLE FORM GOES HERE`);
if (res.status === 200) {
return {
status: 200,
body: { message: 'success' }
};
} else {
return {
status: 404,
body: { message: 'failed' }
};
}
};
Any help would be greatly appreciated!
The fix is, in fact, relatively simple, and involved only a tiny change to the existing code. I had to access event.request (destructured to request), and proceed from there, prompted by this answer to a similar question. So, after that, contact.json.js looks like...
export const post = async ({ request }) => {
const body = await request.formData();
const name = body.get('name');
const email = body.get('email');
const message = body.get('message');
const response = await fetch(`URL TO RELEVANT GOOGLE FORM GOES HERE`);
if (response.status === 200) {
return {
status: 200,
body: { message: 'success' }
};
} else {
return {
status: 404,
body: { message: 'failed' }
};
}
};
(Note, too, that this whole form was based upon this video by WebJeda, which won't now work with the latest SvelteKit build, but will with this simple alteration.)

UI update with GET method

I'm working on a project to get the api from openweathermap using node js & express & then update the UI.
I'm trying to update the UI of the page with the GET data, but it does not work. it prints undefined instead of the required values.
it works and gets the api from openweathermap on the terminal & console.
any help would be appreciated!
/* Global Variables */
const date = document.getElementById('date').value;
const temp = document.getElementById('temp').value;
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();
//baseURL & apiKey
const baseURL = `http://api.openweathermap.org/data/2.5/weather?zip=`;
const apiKey = `&appid=...`;
//event listener when user clicks generate button
const button = document.getElementById('generate');
button.addEventListener('click', performAction);
//event listener function
function performAction(event) {
const zip = document.getElementById('zip').value;
const feelings = document.getElementById('feelings').value;
getData(baseURL, zip, apiKey)
.then(function (data) {
console.log(data);
postData('/add', {date: newDate, temp: data.main.temp, feelings: feelings});
updateUI();
})
};
//function to fetch api data
const getData = async (baseURL, zip, apiKey) => {
const res = await fetch(baseURL+zip+apiKey)
try {
const data = await res.json();
return data;
console.log(data);
}catch(error) {
console.log("error", error);
}
}
// user input post data function
const postData = async (url = '', data = {}) => {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
try {
const newData = await response.json();
}catch (error) {
console.log("error", error);
}
};
//updating UI
const updateUI = async () => {
const request = await fetch('/all');
try{
const allData = await request.json();
document.getElementById('date').innerHTML = allData.date;
document.getElementById('temp').innerHTML = allData.temp;
document.getElementById('content').innerHTML = allData.content;
}catch(error){
console.log("error", error);
}
}

Categories

Resources