Fetch doesn't retrive data
I am currently building a login form which will be using a restAPI for the registration/Auth but I'm receiving a 401 error when using fetch to test the retrieved data.
console.log(fetch('http://localhost:5000/users/'), {
method: 'get',
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json()) .then(json => console.log(json))</code>
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
-
How to convert String having key=value pairs to Json
myString =
{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00};
I want to convert it to the following string.
{"AcquirerName": "abc", "AcquiringBankCode": 0.2, "ApprovalCode": 0};
How can I do it in java?
-
NextJS: Error serializing `.data.data` returned from `getServerSideProps`
I'm new to NextJS. I'm working on a simple page in which I need to retrieve data from my backend app. My backend app is a totally separate app written in go. My undestanding is that I must use
getServerSideProps
to get data from the server on load, so I've got the following:myProject/pages/category/new.js
:export default function AddNewCategory(data) { ... } export const getServerSideProps = async () => { const data = await getAllCategories(); console.log(await data) return { props: { data: { data } } }; };
myProject/api/category.js
:import axios from "axios"; // getAllCategories returns a list of all active categories export const getAllCategories = async() => { axios.get("http://127.0.0.1:8080/api/v1/categories") .then(function (response) { console.log(response.data) return response.data; }) .catch(error => { console.error("error") console.log(error) }) }
As you can see I've got a print statement in
getAllCategories
which prints:{ data: [ { id: 1, name: 'Pop', slug: 'pop', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:00-04:00', updated_at: '2022-05-03T19:50:00-04:00', deleted_at: null }, { id: 3, name: 'Pop 2', slug: 'pop-2', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:24-04:00', updated_at: '2022-05-03T19:50:24-04:00', deleted_at: null } ] }
yet I'm getting the following error:
error - Error: Error serializing
.data.data
returned fromgetServerSideProps
in "/category/new". Reason:undefined
cannot be serialized as JSON. Please usenull
or omit this value.I saw around that I should try to convert the data to string and then back to json:
return { props: { data: JSON.parse(JSON.stringify(data)) } };
but when I do this I'm getting a different error:
error - SyntaxError: Unexpected token u in JSON at position 0
I'm using
next@12.1.5
Any idea what's going on?
-
Images with Firebase and Python Flask API
I am currently developing an API using Firebase from google and Python's Flask libraries. It is a proyect where I am in need of saving images to the DB and then adress them in the API. I would also like to know how to relate the image to an item in the database, say posting an image of Juan, and that is linked with ALL the information from Juan inside the DB. Thanks!
-
Need help finding an api or real world data related to read time of people
I need to create a project for which I require real world data of reading time per page or article. Can anyone help me find data or api in which I can get this data I tried to search for some api but they had information related to books instead of their reading time of a person.
-
Using Websocket Channel in React
I am working on a project where I have to make an api call to a websocket, and display certain information based on that call. As you can see I have used the subscribe portion of the channel in my call. Now I'm not sure what to do if anything with the 2nd two set of bracket. Do I need to include them my call as well, or do they come along with the subscription? And from which of them would I be using the information I need to display? In other words which one is the information I am recieving?
'''
const ws = new WebSocket("wss://ws-feed.exchange.coinbase.com"); const apiCall = { type: "subscribe", product_ids: [ "ETH-USD", "BTC-USD" ], channels: ["level2"] }; ws.onopen = (event) => { ws.send(JSON.stringify(apiCall)); }; ws.onmessage = function (event) { const json = JSON.parse(event.data); console.log(`[message] Data received from server: ${json}`); };
'''
-
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). -
How to verify user based on reCAPTCHA user response and secret key in react.js?
When reading the documentation, the following methods of verifying the user are shown: For web users, you can get the user’s response token in one of three ways:
g-recaptcha-response POST parameter when the user submits the form on your site
grecaptcha.getResponse(opt_widget_id) after the user completes the reCAPTCHA challenge
As a string argument to your callback function if data-callback is specified in either the g-recaptcha tag attribute or the callback parameter in the grecaptcha.render method
How would I do any of those three in react.js, given that I have a token and the secret key?
When visiting the url from which the json is to be gathered, the following is found:
{ success: true, score: 0.9, domain: localhost, }
How would I get the score in this case?
I have tried the following:
const response = await fetch(url); var data = await response.json();
This produces a typeerror however, (failed to fetch).
-
Response tag with URL parameter
Is there any way in an Insomnia request to use the response body of a sub-request in the request body, and at the same time specify a URL parameter for that sub-request?
Consider an API with endpoints like these:
[GET]
_.base_url
/customers/{id}
[GET]_.base_url
/products/{id}
[POST]_.base_url
/invoicesWhen
POST
ing to theinvoices
endpoint, the API expects a JSON body along these lines (highly simplified, of course):{ "date": "2022-03-31", "currency": "USD", "customer": { "id": 123, "name": "Something Corp.", "address": "Here, there and everywhere" }, "items": [ { "id": 456, "description": "Thingamajig", "price": 11500 }, { "id": 789, "description": "Doodad", "price": 23900 } ] }
That is, it expects the
customer
field and each of theitems
fields to be full objects, not just IDs. (And yes, that’s stupid and not RESTful, but I don’t control the API.)The proper way to retrieve such objects would obviously be to call the two GET endpoints with the IDs as part of the URL, and then using the responses as response tags in the POST request – but I cannot find a way to do this.
There’s a lengthy GitHub discussion on per-request veriables which has so far not produced any results, but even the suggested PR in that thread doesn’t seem like it would support defining the URL parameters when calling the request, rather than in the request itself.
Is there some way to achieve this in Insomnia?
-
Cannot POST /users/add in insomnia and postman
Here is my user schema:
const mongoose=require('mongoose'); const userSchema=new mongoose.Schema({ username:{ type: String, required: true, unique: true, minlength: 3, }, password:{ type: String, required: true, minlength: 8 } }) const User=mongoose.model('User', userSchema); module.exports = User;
And here is my users router:
const router = require('express').Router(); const bodyParser = require('body-parser') let User= require('../models/userSchema'); router.route('/').get((req,res)=>{ User.find() .then(users => res.json(users)) .catch(err => res.status(400).json('Error:'+err)); }); router.route('/add').post((req,res)=>{ const username=req.body.username; const password=req.body.password; const newUser=new User({username, password}); newUser.save() .then(()=>res.json('User added!')) .catch((err)=>res.status(400).json('Error:'+err)); }); module.exports=router;
Whenever I post this in insomnia or postman, I get an error Cannot POST /users/add even though I'm successfully connected to server and to MongoDB
{ "username":"John", "password":"password1234" }
-
GraphQL API Error 403 when using Apps Script or Python, fine using Insomnia
I am trying to access the Pulsar GraphQL API using Apps Script (Have also tried Python) however, it returns a 403 error each time. I have run the exact same query and variables through Insomnia, with the same API token and it returns the desired data. Any help would be greatly appreciated!
function getDataTrac() { var url = 'https://data-explorer.pulsarplatform.com/graphql/trac'//+endpoint; var body = { 'query' : 'query Results($date_2021_01_01: Filter!,$date_2021_01_01_option: Option){results(filter: $date_2021_01_01, options: $date_2021_01_01_option) { total nextCursor results{ pulsarId pulsarParentId identifier parentIdentifier createdAt publishedAt deletedAt updatedAt source info language countryCode domainName url content rejected rejectedBy images videos hashtags tags topics communities emotion reactionsByType impressions viewsCount engagement engagementRate commentsCount likesCount sharesCount cachedReactionCount visibility sentiment csr reputation reviewRating } }}', 'variables' : '{ "date_2021_01_01": { "dateFrom": "2021-01-01T00:00:00Z", "dateTo": "2021-01-02T23:59:59Z", "searches": [ "88dcc5a4bd60facf01829dc481c65c8e" ] }, "date_2021_01_01_option": { "limit": 1 }}' } //query = query.replace(/[\s\t\n]{2,}/," "); //vars = vars.replace(/[\s\t\n]{2,}/," "); //Logger.log(query); //url = url + '?query=' + encodeURI(query) + '&variables=' + encodeURI(vars); var options = { 'headers': {'Authorization' : 'Bearer ***API Token***'}, 'muteHttpExceptions': false, 'contentType': 'application/json', 'method': 'POST', 'payload' : JSON.stringify(body) }; var response = UrlFetchApp.fetch(url,options); Logger.log(response) }