JavaScript fetch api: TypeError failed to fetch
I'm creating a blog with a friend as a small project between us. I'm and tested the backend in PHP, he's writing the frontend code. As he is still newer than me HTML and JS, I'm also writing the JS code to handle comms with the backend. The issue we're facing and can't get our heads around is the following: Logging in is possible with username or email and the password. The login code works when
- Username - password with curl
- Email - password with curl
- Username - password with Postman
- Email - password with Postman
- Username - password with vanilla JS fetch
What doesn't work is the Email - password with vanilla JS fetch. In this case we get the TypeError: Load failed or Failed to fetch. This is the JS code:
const credential = document.getElementById('email').value;
const password = document.getElementById('password').value;
const body = JSON.stringify({ credential, password });
fetch('/api/auth/login', { method: 'POST', body: body, headers: { 'Content-Type': 'application/json; charset=UTF-8' } })
.then((res) => res.json())
.then((data) => {
if (data.access_token) {
localStorage.setItem('fit_token', data.access_token);
} else {
alert(data.message);
}
})
.catch((err) => console.log(err));
};
The catch isn't even reached, nothing gets logged in console. I only see the error when I debug...
Can anyone point us in the right direction?
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
MarkLogic server-side JavaScript and XQuery
I am just starting using NoSQL MarkLogic DB and trying to choose for me the best query language to learn and use in future. On server side MarkLogic provides the possibility to use JavaScript API or XQuery API.
I want to receive an advice. Which language is better to concentrate on and learn? JavaScript or XQuery?
- Popover in chrome extension using js
-
Converting PYODBC output into an int
Pulling data from a SQL query that gives me 1 number that is stored in a PYODBC row. I want to then add that number to another variable in the file. Pseudocode below -
prev = 5 cursor.execute("select statement") pulledNumber = cursor.fetchall() value = [row[2] for row in pulledNumber] final = prev + value
Getting a type error (list and int operation). Tried to cast the list to an int a few different ways but could not get it to work
-
TypeError: list indices must be integers
I'm trying to insert an item from one list to another and using an item from a list of numbers for the index but I'm getting this error even though I'm using integers for index numbers
and the other thing is that the same item is accepted as an index in the line just before the error
I even tried putting a number there just to test it but it gave me the same error
here's the code:
FoundLetters = ['p', 'l', '-', 'i', 'n'] MissingLetters = [] AllLetters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] def MissingCount(): for j in range(len(FoundLetters)): if FoundLetters[j] == '-': MissingLetters.append(int(j)) def iterate(): for i in range(len(AllLetters)): for i in AllLetters: FoundLetters.pop(MissingLetters[0]) FoundLetters.insert(MissingLetters[0], AllLetters[i]) MissingCount() iterate()
and this was the exact error:
Traceback (most recent call last): File "main.py", line 26, in <module> iterate() File "main.py", line 22, in iterate FoundLetters.insert(MissingLetters[0], AllLetters[i]) TypeError: list indices must be integers or slices, not str ** Process exited - Return Code: 1 ** Press Enter to exit terminal
-
Getting Error with UI for TikTok algorithm
So I basically made a algorithm which takes the users input and decided on a rank from 1-100 and puts it on a UI.
import tkinter, os, webbrowser, random #algorithm def tiktok_algorithm(share_count, like_count, comment_count, posts): if (share_count >= 10000 and like_count >= 5000 and posts >20 and comment_count.find("amazing")!= -1): rank = 1 elif (share_count >= 7000 and like_count >= 2000 and posts >25 and comment_count.find("amazing")!= -1): rank = random.randint(2,10) elif (share_count >= 6000 and like_count >= 1500 and posts >25 and comment_count.find("amazing")!= -1): rank = random.randint(11,20) elif (share_count >= 5000 and like_count >= 1300 and posts >20 and comment_count.find("amazing")!= -1): rank = random.randint(21,40) elif (share_count >= 4000 and like_count >= 1000 and posts >15 and comment_count.find("nice")!= -1): rank = random.randint(41,55) elif (share_count >= 3000 and like_count >= 500 and posts >11 and comment_count.find("cool")!= -1): rank = random.randint(56,70) elif (share_count >= 2000 and like_count >= 300 and posts >11 and comment_count.find("ok")!= -1): rank = random.randint(71,80) elif (share_count >= 1000 and like_count >= 150 and posts >11 and comment_count.find("ok")!= -1): rank = random.randint(81,90) elif (share_count >= 400 and like_count >= 100 and posts >11 and comment_count.find("ok")!= -1): rank = random.randint(91,97) else: rank = random.randint(98,100) return(rank) def calculate_ranking(): # read in the entry values like_count = int(likes_entry.get()) comment_count = comment_entry.get() posts = int(posts_entry.get()) shares = int(share_entry.get()) rank = tiktok_algorithm(like_count, comment_count, shares, posts) # "print" result to result label result_label.config(text="Your tiktok ranking is: " + str(rank)) root = tkinter.Tk() root.title("Magic Tiktok Algorithm") root.geometry("400x600") # likes likes_label = tkinter.Label(root, text="Number of Likes:") likes_label.pack() likes_entry = tkinter.Entry(root) likes_entry.pack() # comment comment_label = tkinter.Label(root, text="Comment:") comment_label.pack() comment_entry = tkinter.Entry(root) comment_entry.pack() #shares share_label = tkinter.Label(root, text="number of shares:") share_label.pack() share_entry = tkinter.Entry(root) share_entry.pack() #posts posts_label = tkinter.Label(root, text="Posts") posts_label.pack() posts_entry = tkinter.Entry(root) posts_entry.pack() #image img_path = os.path.dirname(__file__) + "\\tiktok-tricks-09.PNG" tiktok_image = tkinter.PhotoImage(file=img_path) resized_tiktok_img = tiktok_image.subsample(4,4) image_label = tkinter.Label(root, image=resized_tiktok_img) image_label.pack() # rank button rank_button = tkinter.Button(root, text="Get Ranking", command=calculate_ranking) rank_button.pack() # result result_label = tkinter.Label(root, text = "Your tiktok ranking is:") result_label.pack() # keep the UI running root.mainloop()
I keep getting this error, I have tried casting it to an integer, but it still doesn't work can anyone help: Do I need to change the top to str(tiktok_algorithm)
typeError: '>=' not supported between instances of 'str' and 'int'
-
Using Fetch api to check remote database connection Node.js
So i am trying to use fetch to check if the information that was entered in the form was valid and that we are able to find and connect to this db. Also using SweetAlert2(https://sweetalert2.github.io/)
this are my routes for the /addDB page
router.route('/addDB') .get(checkAuthenticated, function (req, res) { res.render("dashboard/addDB", { }); }) .post(checkAuthenticated, async function (req, res) { var syscheck = req.body.sysCheck; if (syscheck == "on") { syscheck = true } else { syscheck = false } let nickname = req.body.dbName; let sid = req.body.dbSid; let host = req.body.dbIP; let port = req.body.dbPort; let username = req.body.dbUser; let password = req.body.dbPassword; try { let connectAndGetData = await ConnectorServerFunctions.writeToDbOnPost(sid, host, port, username, password, syscheck) if (connectAndGetData.extdb_connection) { await User_database.query().insertGraph({ db_nickname: nickname, db_sid: sid, db_host: host, db_port: port, db_username: username, db_password: password, db_asm: syscheck, db_version: connectAndGetData.extdb_data.version.VERSION, db_status: "online", db_size: { db_free: connectAndGetData.extdb_data.dbSize_data.Free_Space, db_used: connectAndGetData.extdb_data.dbSize_data.Used_Space, db_total: connectAndGetData.extdb_data.dbSize_data.Free_Space, }, db_tablespace: [ { db_table_name: connectAndGetData.extdb_data.tablespaceResultorg[0].TABLESPACE_NAME, db_table_used: connectAndGetData.extdb_data.tablespaceResultorg[0].USED_SPACE_GB, db_table_size: connectAndGetData.extdb_data.tablespaceResultorg[0].TABLESPACE_SIZE_GB, db_table_pct: connectAndGetData.extdb_data.tablespaceResultorg[0].PERCENTAGE_USED, }, ... ] }).then(async()=>{ res.json({connection:connectAndGetData.extdb_connection, dataInsert: true }) }) // res.redirect("/"); }else{ res.json({connection:connectAndGetData.extdb_connection}) } } catch (e) { console.error(e); } });
This is my html for the form and the script that i am using to
async function fetchConnectionStatusJSON() { const response = await fetch('/dashboard/addDB',{method:'POST', headers: {'Accept': 'application/json', 'Content-Type': 'application/json' }}); const ConnectionStatus = await response.json(); return ConnectionStatus; } element = document.getElementById("Submit") element.addEventListener("click", function (e) { e.preventDefault() Swal.fire({ title: 'Are you want add this database?', text: "Make sure the db information is correct.", icon: 'question', showCancelButton: true, confirmButtonColor: '#65d672', // cancelButtonColor: '#d33', confirmButtonText: 'Yes', allowOutsideClick: false, }).then((result) => { if (result.isConfirmed) { Swal.fire({ allowOutsideClick: false, icon: 'info', text: 'Trying to connect to database...', showConfirmButton: false, }); document.testform.submit(); } }).then( () => { fetchConnectionStatusJSON().then((ConnectionStatus) => { if(ConnectionStatus.connection){ Swal.fire({ allowOutsideClick: false, icon: 'info', text: 'Getting database infomation...', timer:2000, showConfirmButton: false, }).then(() => {window.location.href="/";}) }else{ Swal.fire({ allowOutsideClick: true, icon: 'error', text: 'Connect to database failed. Please ensure you are on the right network and your information is correct.', showConfirmButton: false, showCloseButton:true }); } }); }) })
<form action="./addDB" name="testform" method="POST"> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">DB name (Nickname)</label> <input type="text" class="form-control" name="dbName"> </div> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">DB SID/Service Name</label> <input type="text" class="form-control" name="dbSid"> </div> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">DB Host/IP address</label> <input type="text" class="form-control" name="dbIP" aria-describedby="emailHelp"> <div id="emailHelp" class="form-text">You have to be on the same network for a valid IP.</div> </div> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">DB Port</label> <input type="text" class="form-control" name="dbPort" aria-describedby="emailHelp"> </div> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">DB username</label> <input type="text" class="form-control" name="dbUser"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">DB Password</label> <input type="password" class="form-control" name="dbPassword"> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" name="sysCheck"> <label class="form-check-label" for="sysCheck">Check if database use asm.</label> </div> <button type="submit" id="Submit" class="btn btn-dark">Submit</button> </form>
I am new fetch and so confused on what to do with fetch here, should i even be having the method as a POST or something else. At the moment implementing this just returns JSON to the browser with the connection variable as true or false instead of redirecting to "/" page or just displaying the sweet alert/modal saying that the connection failed. Mostly likely due me submitting the form early (
document.testform.submit();
), but how else would i insert the values needed to check the connection. The ConnectorServerFunctions.writeToDbOnPost() returns 2 variables, one with Boolean value showing if it was able to connect and another variable with all the relevant data for the db(if connection is successful). -
I want to upload a large file to MongoDB using jQuery
I need help to upload large zip file (compressed) and save it to my MongoDB:
<form action="./uploid" method="post" id="uploadForm" enctype="multipart/form-data" class="mx-auto"> <div class="input-group mb-3 "> <input type="file" id="inpFile" name="inpFile" /> </div> <input id="uploid" type="submit" class="btn btn-primary"/> </form>
-
How to verify ReCAPTCHA token in js?
I have written the following function in js to verify a ReCAPTCHA token:
export async function validateHuman(token) { const secret = "funny_little_secret"; const response = await fetch( "https://www.google.com/recaptcha/api/siteverify?secret=" + secret + "&response=" + token, { method: "POST" } ); const data = response.json(); return data.success; }
For reasons I do not understand, I get a fetch error while running this. I have looked in to a few other versions of the functions but have not yet found a solution.
Moreover, the token is correct and is produced according to the documentation, so I am wondering whether there is something wrong about my secret, as I have seen others use something along the lines of
process.env.secret
, which I have tried without success, or it there is something I do not understand about the fetch function.This is the complete error:
Uncaught TypeError: Failed to fetch validateHuman @ http://localhost:3000/static/js/bundle.js:3384:26
thanks in advance