Perform a GET Request in React.js - javascript

Well I'd like to perform a GET Request of this URL: localhost:8080/home/data. Well if I'd like to access this URL i have to authenticate with a username and a password.
This is my code:
getDataAxios(){
axios.get('localhost:8080/home/data', {
auth: {
username: 'user.user#provider.com',
password: 'password'
}
})
.then(function (response) {
console.log(response);
})
}
And if I press a ceratin button on the React.js website the data which will come from that url should be displayed on the console. Somehow it is not working with this error:
Uncaught TypeError: Cannot read property 'get' of undefined
BTW. The backend is working. I verified it with Java.

That error seems to be coming from the axios library, instead of an error in your backend or something. The Uncaught TypeError means is that the axios library is not been imported properly, or the scope where you're invoking axios is not accessible. Check that you're importing the library on your React component. It should be something like:
import axios from 'axios';
In the top of your component.

Related

Uncaught (in promise) SyntaxError (VueJS with OpenWeatherMap API)

Im trying out a weather app with VueJS using the weathermap API. I already got my API key and I still doesn't work on my application. But when I try to use the link for the API in the browser, it shows data in it. But why it doesn't show data in my app. I checked the browser console it display an error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Here is my code:
export default {
name: 'App',
data(){
return{
api_key: 'f9874496f4c1c5729fc7b4f546b1ebe4',
url_base: "api.openweathermap.org/data/2.5/",
query: '',
weather: {}
}
},
methods: {
fetchWeather(e) {
if(e.key == "Enter") {
fetch(`${this.url_base}weather?q=${this.query}&units=metric&appid=${this.api_key}`)
.then(res=> {
return res.json();
}).then(this.setResults);
}
},
setResults (results) {
this.weather = results;
}
}
}
And here is a photo of the API link I used in the browser.
check it here
I hope someone could help me out with this. Thanks in advance!
you need to catch your errors and print it to find out exactly what is wrong.
fetch(`${this.url_base}weather?q=${this.query}&units=metric&appid=${this.api_key}`)
.then(res=> {
return res.json();
})
.then(this.setResults)
.catch(error=>console.log(error))
this should get rid of the uncaught(promise) error and print the actual error
This must be from "Tyler Potts" Vue weather app tutorial on YouTube. I was stuck here too.
Your url_base needs to include http:// at the beginning:
url_base: 'http://api.openweathermap.org/data/2.5/',
Edit
I believe this is because while we may be used to our browsers including the "http://" protocol at the beginning, so that all we need to do as users is type in the hostname and domain to access a website or data we wish to retrieve, our code will not automatically do the same. So you must specify exactly and fully what the function must fetch.

registering a service worker in react

Our server is setup as follows, using react, graphql, mongo and express:
public
index.html
service.js
src
assets
client (has 2 client side js files)
components (for react)
game.jsx
server (graphql server)
server.js
I need to register a service worker so that I can send push notification to players; the call is from game.jsx (the one that gets loaded when I want the serviceWorker to be registered):
const swreg = await navigator.serviceworker.register('service.js');
This causes a get request to ourURL.com/service.js (hence why I have service.js under public, as that's where it's served)
This is fine and dandy, but then I keep getting import errors in service.js:
Uncaught SyntaxError: Unexpected token {
this is the offending code in service.js:
import { saveSubscription } from "src/queries/queries";
Where saveSubscription is a graphql mutation call, and is defined in src/queries/queries.js.
I have tried other forms of importing, but they give me a syntax error of somekind. Googling told me that I need a type="module" tag, which obviously does not apply to this case.
How can I solve this problem? Thanks!
I fixed it... sort of.
I removed the import line, and instead used a fetch within the function.
fetch(url, {
method: "POST", // get can't have body
'Content-Type': 'application/graphql',
body: JSON.stringify({graphQLQuery})
});

How to call axios/api call in Nativescript application

I'm trying to build a small application on Nativescript-vue where I'm having backend laravel framework for api calls which needs to be called to get relevant data. For example if user wants to login he needs to validate its credentials through api oauth/token so I'm trying to call this through axios here is my code:
My settings.js file contains.
export const authHeader = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
this is being imported inside my axios calls:
const postData = {
grant_type: 'password',
username: user.email,
password: user.password,
client_id: clientId,
client_secret: clientSecret,
scope: '',
provider: provider
}
const authUser = {}
axios.post(authUrl, postData, {headers: authHeader}).then(response => {
console.log('Inside oauth/token url')
if(response.status === 200)
{
console.log('response received')
}
})
.catch((err) => {
if(err.response.status === 401){
reject('Validation error')
}
else
reject('Something went wrong')
})
when I try to build with command tns debug android --bundle I get chrome-devtools which shows me:
Digging more deep into it I can see headers are being passed but those are only provisional:
As you can see I've console.log inside my application which show me:
Even while compiling I get following errors:
Guide me how can I achieve this. Thanks.
Edit:
Similarly I used nativescript's own http documentation something like this:
const httpModule = require("http");
httpModule.request({
url: "http://iguru.local/oauth/token",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
grant_type: 'password',
username: this.user.email,
password: this.user.password,
client_id: 'check',
client_secret: 'check',
scope: '',
provider: 'check'
})
}).then((response) => {
// Argument (response) is HttpResponse
console.log('Action called')
if(response.status === 200)
{
console.log('Response recieved')
}
}, (e) => {
console.log('Something went wrong')
});
I'm getting the same result, moreover I tried api from server end ex http://confidenceeducare.com/oauth/token it happens to be same. Normal Vue application calls the api perfectly fine. I guess there is some problem with the nativescript application. Do I need to import something more? I'm stuck with it.
If anybody is thinking my api end point is broken, I tried using the urls mentioned in example i.e. https://httpbin.org/post:
and:
When I checked my api in postman it is working over there, I'm getting at least a response with status code:
Edit 2:
For reference github repository https://github.com/nitish1986/sample_mobile_app
I tested the exact same project you have shared in Github with Android 8.0, it works perfectly fine. The axios call hits the error block as the response status (error.response.status) is 401 and data (error.response.data) returns the exact same response you see from Postman.
If you are using Android 9 or later it might fail as you haven't enabled useCleartextTraffic on your application tag in the AndroidManifest.xml.
<application
android:usesCleartextTraffic="true"
android:name="com.tns.NativeScriptApplication"
With iOS also it would fail as you haven't enabled app transport security. Just to allow all Http communication within your app, you have to add the following key to your info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
In case if you want to allow only specific domains, then use NSExceptionDomains key and list the endpoints.
The problem has to do with how axios is imported. Try:
import axios from 'axios/dist/axios'
this also solves the Module not found: Error: Can't resolve 'net' in... error.
When importing the package normally my requests failed, returning the error
Error in v-on handler (Promise/async): "Error: Request failed with status code null"

Axios GET route 404-ing, Node.js/Express

I have the following simple GET inside a function.
axios
.get(`/api/search/q=${this.value}`)
.then(res => {
console.log(res.data);
});
The GET 404's if I enter a query (the letter 'a' in this case):
GET http://localhost:7777/api/search/q=a 404 (Not Found)
so, of course I get an Uncaught promise error from the .then:
Uncaught (in promise) Error: Request failed with status code 404
I figured that it must be a simple routing problem, but my express route is:
router.get('/api/search', someController.someFunction)
The function in the controller works (ie responds with the data) as I have used it elsewhere in the app, so I feel that I have narrowed it down to the axios GET not finding the api. But I can't figure out why, as the path looks OK to me.
You were 404 getting because node is expecting only /api/search but your trying /api/search/:q which is different altogether, try
axios.get('/api/search/', {
params: {
q: value
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
since any number of parameters added will not make the URL clumsy, an alternate for
axios.get('/api/search?q=${this.value}').
and on the server
router.get('/api/search', someController.someFunction)
and in your controller
if(req.query.hasOwnProperty('q')){
var q = req.query.q;
}

Loopback Angular SDK Login Issue

I created a "user" named model with base class "User". I'm trying to login a user in Angular App using lb-ng generated service but it's not logging in.
In my Login controller I invoked User.login() providing email and password but its giving some weird error.
Even I included this code in my app.js
// Use a custom auth header instead of the default 'Authorization'
LoopBackResourceProvider.setAuthHeader('X-Access-Token');
// Change the URL where to access the LoopBack REST API server
LoopBackResourceProvider.setUrlBase('http://.../api');
In loginController
console.log(User.login({ email: "shah.khokhar#hotmail.com", password: "12345" }));
But it's giving this validation error:
Kindly help me on this.
Thanks,
If you could post your user.json file and your actual angular code then it would be more clear. But as far as I can see, there are things you are doing wrong.
You are making a request to User model instead of your custom user model which obviously won't work as your user data is present in your custom model and not the built in User model
You are most probably making a POST request to a wrong method than login method as login method request url looks something like this
http://localhost:3000/api/users/login
Here's a working sample code for login function which I use for my project
self.login = function () {
var data = {
email: self.email,
password: self.password
};
users.login(data).$promise
.then(function (user) {
$state.go('home');
})
.catch(function (err) {
$state.go('auth.register');
});
};
Hope this helps.

Categories

Resources