Can URL API endpoint self-correct? - reactjs

I am using fetch API inside a React application to retrieve and display some quiz questions.
This is my url endpoint: https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple
I have noticed that:
-when I misspell part of the URL before "?" then the response doesn't get back.
example:https://opentdb.com/api.ph?amount=${amount}&difficulty=${difficulty}& (missing "p" of php)
-when I misspell part of the url after "?" then, sometimes I get an empty array back, sometimes I get the data back. How can I get data back with a wrong URL?
example: https://opentdb.com/api.php?amoun=${amount}&difficulty=${difficulty}&type=multiple (missing "t" in amount)
I haven't deployed the application yet, I am using vsc and run npm start to develop the application.
Is it possible that the URL auto-corrects? or maybe it gets cached?
my code:
export const fetchQuizQuestions = async (
amount: number,
difficulty: Difficulty
) => {
const endPoint = `https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`;
try {
const response = await fetch(endPoint);
console.log(response);
const data = await response.json();
console.log(data);
if (data.results.length === 0) {
throw new Error("The part after ? contains some mistake");
}
//below I create the new property "all_answers" and make sure the answers order is never the same
return data.results.map((question: Question) => ({
...question,
all_answers: shuffleArray([
...question.incorrect_answers,
question.correct_answer,
]),
}));
} catch (error: any) {
console.log(error.name);
console.log(error.message);
}
};

Before the ? It's the url. So if you make a mistake there, basically it's like sending a letter to a different adress, so you will not get any answers.
After the ? it's the query string. So you're asking for a result, with some parameters (your query)
So if you're saying like "ok, send me back answers with amount = XXX" but you misspell amount, it's just like "ok send me back answers" because you're not asking for amount anymore (but amoun which is nothing for the endpoint)

Related

Error handling response: Error: Blocked a frame (...) from accessing a cross-origin frame

I am fetching a calendly embed link dynamically into a next.js13 app, and technically, it is working. However, sometimes the embed doesn't fetch, resulting in a screen that looks like this:
ONLY upon refresh, the embed populates, and the console shows the error:
After doing some research, it seems as though this could be a CORS issue, though I am not sure. The way the embeds are pulled in is from supabase, through a fetch function and then passed to the static page like so:
export default async function HostPage({
params: { username },
}: {
params: { username: string };
}) {
const { data: profile } = await supabase
.from("profiles")
.select()
.match({ username })
.single();
const [host] = await Promise.all([profile]);
return (<div
data-url={profile.calendar_embed}
></div>)
To recap:
Sometimes, the embed gets fetched and displays right away. Errors are shown in the console
Some other times, the page remains empty, no errors in the console.
Upon refresh, the embed appears, with errors in the console.
Does anybody have an idea and can point me in the right direction?
Thanks in advance.

Why does ASP.NET Core 6 MVC Route handler not accept data from axios post request?

I want to post an id to the backend and get the expected result, so
here is the code in the frontend side :
import axios from "axios"
export async function getList(val) {
return await axios.post('http://localhost:5107/PlantsInfo', { id:val }).then(({ data }) => {
return data;
});
}
and in the backend, I have code something like this:
app.MapPost("/PlantsInfo", ([FromServices] DastShafaContext context, int? id) =>
{
// database interaction code according to the id
}
When I attempt this and check it by setting a breakpoint, it takes a request but without an id (that is null)...
But when I attempt to pass an id through Postman, everything is okay.
I think it seems the main problem is related to Axios.
How can I fix it?
This is how my problem was solved!
return await axios.post('http://localhost:5107/GetPlantInfoById?id=' + val).then(({ data }) => {
return data;
});
But this is not the standard way.
I still welcome the best way

How can I post form data from react to an express.js server and use it as part of a url string

Just to make this clearer. I have a form where the user inputs a name which is passed to the apiUrl const to become part of the URL string. The form input data is passed through state as {this.state.input}. After the user inputs the form with the name he wants to search for, he clicks a button which calls the onButtonSubmit function that fetches the data with the updated apiUrl parameters. The catch is, this is running on the front-end and as this is a proprietary api, I don't want to expose the api key (which is part of the url) to the user.
I have set up an express.js server but I'm still unsure on how I can post the form data to it and then use that in the same manner used in my code below.
onButtonSubmit = () => {
const apiUrl = 'URLStringPart1' + this.state.input + 'URLStringpart2withAPIKey';
fetch(apiUrl)
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
array1: result.array1,
array2: result.array2,
array3: result.array3,
array4: result.array4,
array5: result.array5,
route: 'fetched'
});
},
error => {
this.setState({
isLoaded: false,
error: error
});
}
);
}
So the output I'm looking for would follow something like this:
Post form data from frontend after the user submits it with a
button click
Through the backend, after the form data is posted, use it to update the apiurl and then fetch the data from the api(using axios perhaps)
Send the fetched data back to the frontend
I think you need to use prams, in your express server the API route should look like this: api/users/:name --> returns user with this name.
Then try fetching this API by sending the request to the server like this:
http://locahost:8000/api/users/${this.state.name}

Select data from firebase via id gives me a CORS error

I'm deleting data from my firebase db with fetch but I can't figure out how to point to an exact ID.
const deleteHandler = async (id) => {
console.log(id);
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks.json/${id}`,
{
method: "DELETE",
}
);
I tried it this way, but it gives me a CORS error.
I'm also displaying data from this db, that works fine.
UPDATE: I also want to say that when i console.log the id it gives me the correct one.
(Tl;dr: Try adding '.json' to the end of the endpoint.)
I would recommend reading this page to get a general understanding of what a CORS error is and why it might be happening.
In your case, I would recommend using the Firebase SDK that is best suited to your application. You could start here and follow the setup instructions for whichever is most applicable to your use case (perhaps the node client sdk)?
If you must avoid using the sdks for some reason then I would refer to some other Stackoverflow questions such as this one, which suggests that all Firebase REST endpoints need to end with '.json'.
You just need to add .json at the end of your request and remove .json from tasks.json. like this:-
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks/${id}.json`,
const deleteHandler = async (id) => {
console.log(id);
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks/${id}.json`,
{
method: "DELETE",
}
);
Just replace .json text with ${id}.json.
Have a nice day

Fetch status 200 but pending endllessly, except first call

I've been searching to solve this problem for a while but couldn't find a working solution.
I'm making a simple social network website and this API returns a article data such as text, image and video url, etc, all saved in server's local MySQL Database. My front-end is React and server is Nginx reverse proxy with Node.js using Express. When I load the page, I create 5 React components that each make fetch request for given article number.
The following code snippet is the fetch API that asks the server to fetch data from database:
//server-side script
app.get('/api/getArticle/:id', (req, res) => {
const con = mysql.createConnection({
host: 'myhost_name',
user: 'myUser',
password: 'myPassword',
database: 'myDB',
});
con.connect(function (err) {
if (err) {
throw err;
}
console.log("Connected!");
})
const idInterest = req.params.id.toString();
console.log(idInterest)
let sql = 'some_sql';
con.query(sql, function (err, result) {
if (err) {
res.status(500).send("Error while getting article data");
return;
}
else {
res.set('Connection', 'close')
res.status(200).send(result);
console.log("ended")
con.end();
return;
}
})
}
//React script
//index.js
fetch('http://mywebsite.com/api/getMaxArticleId/')//Retrieve top 5 article ID
.then((response) => {
for (let i = 0; i < data.length; i++) {
nodesList.push(<Container articleId={data[i]['id']}/>)
}
ReactDOM.render(<React.StrictMode><NavBar />{nodesList}<Writer writer="tempWriter" /></React.StrictMode>, document.getElementById('root'));
})
//Container.jsx; componentDidMount
const url = "http://mywebsite.com/api/getArticle/" + this.props.articleId.toString();
fetch(url, {
method: 'GET',
credentials: "include",
}).then((response) => {
response.json().then((json) => {
console.log(json);
//processing json data
This used to work very fine, but suddenly the getArticle/:id calls started to show 200 status but 'pending' in 'time' column in Chrome network tab, endlessly, all except the first*getArticle/:idcall. This prevents my subsequent .then() in each Container from being called and thus my entire tab is frozen.
Link to image of network tab
As you see from the image, all pending fetches are missing 'Content Download' and stuck in 'Waiting(TTFB)', except the first call, which was '39'
I checked the API is working fine, both on Postman and Chrome, the server sends result from DB query as expected, and first call's Json response is intact. I also see that console.log(response.json()) in React front-end shows Promise{<pending>} with *[[PromiseStatus]]: "Resolved"* and *[[PromiseValue]]* of Array(1) which has expected json data inside.
See Image
This became problematic after I added YouTube upload functionality with Google Cloud Platform API into my server-side script, so that looks little suspicious, but I have no certain clue. I'm also guessing maybe this could be problem of my React code, probably index.js, but I have no idea which specific part got me so wrong.
I've been working on this for a few days, and maybe I need common intelligence to solve this (or I made a silly mistake XD). So, any advices are welcomed :)

Resources