So I created a website where I used JS and jQuery to send data to a server.
But now I am making that website as an app on my phone using react native.
I've read about the fetch function but I don't completely understand how I would go about it to make this request.
This is the code I used on my website:
$(".btn").click(function() {
var p = $(this).attr('id');
pin: p
$.get("http://192.168.0.129:80/", {
pin: p
});
DisableButtons();
});
Right now I have the following:
sendData = (data) => {
console.log(data);
var p = data;
pin: p
$.get("http://192.168.0.129:80/", { --> this needs to be changed so it could work
pin: p in react native
});
}
So what I want to accomplish is to send this url when I call the function: http://192.168.0.129/?pin=xxx
Thanks in advance
A typical fetch request in javascript looks like this.
const sendData = async(data) => {
const response = await fetch(`http://192.168.0.129:80/?pin=${p}`).then(res => res.json()) //or res.text() if you are expecting text response.
console.log('results')
}
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
So I got the solution, it was simpler then I thought:
sendData = (data) => {
console.log(data);
var url = `http://192.168.0.129:80/?pin=${data}`;
fetch(url);
}
Related
export const getCharactersAsync = createAsyncThunk('getCharactersAsync', async (data) => {
const response = await axios.get('users', { params: { limit: data.limit } });
return response.data;
});
this code block allows me to control limit attribute.
export const getCharactersAsync = createAsyncThunk('getCharactersAsync', async (data) => {
const params = new FormData();
// const params = new URLSearchParams();
params.append('limit', data.limit);
const response = await axios.get('users', params);
console.log(response);
return response.data;
});
However I cannot control limit with using params.append. I tried URLSearchParams instead of FormData but still cannot manipulate limit attribute of the response. Why they differ from each other?
EDIT: This question has missleading information. I should have mention that i am using react-native. I found that react native doesn't fully support everything the web supports. So i need to install package called react-native-url-polyfill.Here is a github issues link
https://github.com/facebook/react-native/issues/23922#issuecomment-648096619
docs
params are the URL parameters to be sent with the request. Must be a plain object or a URLSearchParams object
It can't be FormData
Solution
You wanted to use { params }, not params
export const getCharactersAsync = createAsyncThunk('getCharactersAsync', async (data) => {
const params = new URLSearchParams();
params.append('limit', data.limit);
const response = await axios.get('users', { params });
console.log(response);
return response.data;
});
So I have a small project containing both frontend (html) and backend (express: server, routers) parts. The project isn't that clean, so the its main operationality is launched directly in html section. And not much is clear to me here, especially what function is passed to cb (callback) here?
I have the following code in part of my html page within js project:
const $ = document.getElementById.bind(document)
const request = (path, cb) =>
fetch(path)
.then((res) => {
if (res.ok) return res.json()
throw Error('HTTP error: ' + res.status)
})
.then(cb)
.catch((err) => ($('result').innerHTML = err))
const main = async () => {
const pinRequired = new URLSearchParams(document.location.search).get('pin')
const id = await request(`./qrcode?pin=${pinRequired}`, (json) => {
const { qrbase64, deeplink, pin, id } = json
$('qrcode').innerHTML = `<img src="${qrbase64}" alt="Red dot" />`
$('deeplink').innerHTML = ` ${deeplink.slice(0, 90)}...`
$('pin').innerHTML = pin ? pin : 'Not requested'
return id
})
setInterval(() => request(`./status?id=${id}`, ({ status }) => ($('result').innerHTML = status)), 1000)
}
main().catch(console.log)
Is this (json)? I also don't know why it is in () round brackets, however, it is an object, it cannot be passed as a callback, right?
And I also have a code in another file, which contains /qrcode route of my website. There is a function (quite big, so i'm not posting it, just pointing that it doesn't return function that may be passed as a callback).
If this callback 100% is in another part of the code, as you think, please let me know.
If what you're asking about is this callback (json) => { ... } in the code below:
request(`./qrcode?pin=${pinRequired}`, (json) => {
const { qrbase64, deeplink, pin, id } = json
$('qrcode').innerHTML = `<img src="${qrbase64}" alt="Red dot" />`
$('deeplink').innerHTML = ` ${deeplink.slice(0, 90)}...`
$('pin').innerHTML = pin ? pin : 'Not requested'
return id
});
Then this is what is known as an arrow function. You can read about them here on MDN. They are a shortcut syntax for declaring a function that also has a number of implementation differences.
Note, there are some other issues in your code as request() does not return a promise so it does no good to use await on it and you won't get the id back from return id either.
Also note that the request library has been deprecated and generally shouldn't be used for new code. There is a list of alternatives here, all of which support promises natively. My favorite in that list is the got() library.
I will try and keep this short. I am a current student and have been attempting to retrieve the top 5 posts from the front page of Reddit and display the title and URL on an HTML page. It is probably something really simple, but I can't get it to work. I want to pass the data to my Handlebars template from a single variable. I keep receiving an unhandled promise warning. Here is my code.
let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
.then(res => res.json())
.then(data => {
redditData = [
{
title: data.children.data.title,
url: data.children.data.url_overriden_by_dest
}
];
});
The data object is structured differently than they way you've coded it. Here is how to extract the information you want from the first child:
let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
.then(res => res.json())
.then(data => {
redditData = [
{
title: data.data.children[0].data.title,
url: data.data.children[0].data.url_overriden_by_dest
}
];
});
You might want to check some documentation on how the function fetch works here.
Also, check how promises work here.
That being said, you have to access the object properties, only when the Promise has finished retrieving the data. One way is using the Promise.allSettled function.
Please see the following snippet working, with a slightly different way of organizing it:
const url = "https://www.reddit.com/.json?limit=5";
const promise = fetch(url).then(res => res.json());
function formatHandlebarsData(data) {
const childrenObj = data.value.data.children;
return childrenObj.map(element => ({
title: element.data.title,
url: element.data.url
}));
}
Promise.allSettled([promise]).then(([data]) => {
const handlebarsData = formatHandlebarsData(data);
// You can use the object now
console.log(handlebarsData);
});
Awesome. I was able to get it working with
let url = 'https://www.reddit.com/.json?limit=5';
let settings = { method: "Get"};
let redditData = ""
fetch(url, settings)
.then(res => res.json())
.then(data => {
redditData = [
{
title: data.data.children[0].data.title,
url: data.data.children[0].data.url_overriden_by_dest
}
];
});
Thanks!
I am setting the res.data of an object containerInfo in Vue afer making an axios get request, like so:
methods: {
searchContainers(containerSearch) {
this.containerQuery = JSON.parse(containerSearch.container_query)[0];
this.imageBranch = JSON.parse(containerSearch.container_query)[1];
this.containerInfo["image_branch"] = this.imageBranch
this.url = this.containerQuery.split('/');
axios.get(`http://localhost:8000/get?name=${this.url[0]}/${this.url[1]}/${this.url[2]}&ver=${this.url[3]}`)
.then(res => this.containerInfo = res.data)
.then(this.containerInfo = [...this.containerInfo, this.imageBranch]);
}
I want to add this.imageBranch to the containerInfo object after the data object is received/set in vue.
The issue is that the axios res, once received (takes a few secs), deletes the this.imageBranch key/value added. I know I should probably add it after the promise is resolved but I can't figure out how.
Can someone please help!
Instead of using two .then, use only one and execute all your code inside the arrow function, like this:
methods: {
searchContainers(containerSearch) {
this.containerQuery = JSON.parse(containerSearch.container_query)[0];
this.imageBranch = JSON.parse(containerSearch.container_query)[1];
this.containerInfo["image_branch"] = this.imageBranch
this.url = this.containerQuery.split('/');
axios.get(`http://localhost:8000/get?name=${this.url[0]}/${this.url[1]}/${this.url[2]}&ver=${this.url[3]}`)
.then(res => {
this.containerInfo = res.data;
this.containerInfo = [...this.containerInfo, this.imageBranch]
});
}
I recommend using await/async syntax which is clear and straightforward. So the codes should be like this
async searchContainers() {
const res = await axios.get(`http://localhost:8000/get?name=${this.url[0]}/${this.url[1]}/${this.url[2]}&ver=${this.url[3]}`);
this.containerInfo = res.data;
this.containerInfo = [...this.containerInfo, this.imageBranch];
}
I figured it out. Needed to set a key in object as such: this.containerInfo.image_branch = this.imageBranch
When a user creates a post in my RESTful application, I want to set the response status code to 201.
I followed the documentation and created start/hooks.js as follows:
'use strict'
const { hooks } = require('#adonisjs/ignitor')
hooks.after.httpServer(() => {
const Response = use('Adonis/Src/Response')
Response.macro('sendStatus', (status) => {
this.status(status).send(status)
})
})
Now in my PostController.js, I have this:
async store( {request, response, auth} ) {
const user = await auth.current.user
response.sendStatus(201)
}
But I am getting 500 HTTP code at this endpoint.
What am I doing wrong?
I noticed when I run Response.hasMacro('sendStatus') I get false.
In fact adonis already have this out of the box for all response codes...
Just write response.created(.....).
You can also use for example: .badRequest(), .notFound(), etc...
More info on: https://adonisjs.com/docs/4.1/response#_descriptive_methods
I solved this problem yesterday:
hooks.after.httpServer(() => {
const Response = use('Adonis/Src/Response')
Response.macro('sendStatus', function (status) => {
this.status(status).send(status)
})
})