Unable to get a response from serpStack API using Axios on Chrome - javascript

I have a probleme while i request SerpStack API using Axios on Chrome browser. I don't know if the probleme comes from my code (I may not be using axios properly) or from Chrome config. To explain each time i request SerpStack API i got that error : {code: 105, type: 'https_access_restricted', info: 'Access Restricted - Your current Subscription Plan does not support HTTPS Encryption.'}. And i don't understand why the API told me that, even if i use the http URL. I tested my code on edge and everything work fine on it.
Here is my code :
<script src="https://unpkg.com/axios#1.1.2/dist/axios.min.js"></script>
<script>
const serpStackAPIKey = "MyAPIKey";
const googleSearchRequestInput = document.querySelector('#googleSearchRequestInput')
const googleSearchRequestBtn = document.querySelector('#googleSearchRequestBtn');
googleSearchRequestBtn.addEventListener('click',serpStackAPIGetRequest)
let googleSearchResultDiv = document.querySelector('#googleSearchResultDiv');
function serpStackAPIGetRequest(){
const request = `http://api.serpstack.com/search?access_key=${serpStackAPIKey}&query=${googleSearchRequestInput.value}`;
axios.get(request)
.then(function(response){
console.log(response);
})
}
</script>
Update
By searching in the network console i find that my initial request have a status code of "307 Internal redirect" and that chrome create a second request with https. How can i prevent Chrome or any other browser to do such a thing ?

Related

Inconsistently getting 'FirebaseError: Response is not valid JSON object.'

I'm working on a react-native app with spotify integration. I've set up the oAuth flow w/ auth code grant where I can get the authorization code. I've then set up cloud function on firebase to proxy the actual token exchange (I don't want to reveal my secret to the client!). I've added logs and can see that the function is correctly completing the exchange with the spotify token endpoint, and receiving a refresh and access token.
const tokenRequeset = functions.https.onCall(async (data, context) => {
// spotify network request, error handling, etc here ....
// I want to emphasize that this network request completes
// properly - my log statement below verifies in server logs
// that I'm getting the expected value.
const resp = await axios.post(
"https://accounts.spotify.com/api/token",
QueryString.stringify({
grant_type: "authorization_code",
code: code,
redirect_uri: redirectURI,
}),
{
headers: {
"Authorization": `Basic ${BEARER_TOKEN}`,
"Content-Type": "application/x-www-form-urlencoded",
},
}
);
console.log(resp.data.access_token);
return { status: "success", token: resp.data.access_token };
});
export default tokenRequest
resp.data.access_token is the JWT access token used to hit the spotify API - it's a string value according to the API. (I'd provide an example one, but it is an auth token)
However, when I try to use the firebase/functions package to call my function from my app, I will sometimes get a 'FirebaseError: Response is not valid JSON object.'
What makes this extra fun is that it's inconsistent - yesterday I had the issue, and then it went away (without changing my code!). I was able to hit both the local emulator function and then the deployed function no problem, but today the 'FirebaseError: Response is not valid JSON object.' error is back.
I have checked the logs for the failed invocations both locally and on the deployed function, and in both cases the spotify API call is working - I'm getting all the expected behavior right up until the return (which isn't working for some reason).
On the client side, I'm configuring firebase like so:
const firebaseConfig = {
// Shhhhhh
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const functions = getFunctions(app);
// Uncomment to run locally
connectFunctionsEmulator(functions, "localhost", 5001);
export { app, functions };
And then exposing and calling it like so:
const SpotifyAuth = httpsCallable(functions, "spotify-auth");
const resp = await SpotifyAuth(code, redirectURI)
(I know this isn't full code - I grabbed the relevant portions. Happy to provide more if needed).
I tried looking up this error, and I found results from ~2018/2020 with the old style of firebase/functions, but they seem to be related to region and I'm deployed in the default us-central1 - according to the SDK documentation that means I shouldn't touch it.
The existing solutions to the problem also seem to be based on the old style of function calls, rather than the more recent httpsCallable() and getFunctions(app).
I'm going insane trying to figure out why sometimes I'm getting this error
EDIT:
More information on the error - I ran my code again today and didn't see the error locally, but I DID see it when I hit the deployed function.
Again, I want to emphasize that I think the error is in the firebase network response - if you look at the network request I receive a 200 but the response is empty.
Did an additional full mockup of a function to see what would happen:
const test = functions.https.onCall((data, context) => {
console.log("function call");
return { status: "success", token: "asdfasdfasdfasdfasfs" };
});
export default test;
I'm getting the same error.
UPDATE:
I've given up on using the sdk and onCall method for firebase cloud functions - all of my testing thus far indicates that this is a bug or error on the google cloud function side, and there's nothing I can do from my side.
The good news is the onRequest approach seems to not have this issue - it's behaving properly and reliably.
I really hope that I've messed up along the way and there's a solution I've missed - the SDK seems fantastic and I like the integration it (is supposed to) offer, but as far as I'm aware right now unless there's a bug fix (or update to the documentation if I'm doing something wrong) it seems like it simply won't work.
I'm still planning on using firebase, but from my experience thus far I'd advise anyone early in their server work to consider using another offering (at least if you need to use the functions - I was able to get storage working).

Empty response body with 200 status code for ajax post call only on mobile browser

Thank you in advance. Googled for this issue. Couldn't find a valid solution. I am writing a webapp using vue.js as front end and using AWS lambda functions with api gateway as REST service
As part of webapp, i have a login component which makes ajax call to AWS endpoint. I am using axios.post for ajax call.
Here is code snippet:
loginUser(username, password) {
const vm = this;
var apiUrl = `${this.host}/user/login`;
const requestBody = {
username: username,
password: password,
};
axios
.post(apiUrl, requestBody, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json'} })
.then((response) => {
window.console.log('Login Response')
window.console.log(JSON.stringify(response))
store.dispatch('login', { user: response.data, error: '' });
vm.resultSubject.next(response.data);
})
.catch((error) => {
vm.resultSubject.error('Failed Login');
window.console.log(error);
});
return this.resultSubject;
}
Everything works fine when i login using laptop browser but when trying the same on my mobile browser is giving me empty response. the status code is 200 but no response data. Making a GET call works fine. Attaching some snapshots showcasing the issue
network tab iphone safari - empty response
console tab iphone safari - response logged with actual js file
network tab laptop safari - with response
console tab laptop safari - response logged with data
network tab iphone safari - with response on different GET call
It turns out the main problem is in server code.
Weird behavior in mobile is due to username being camel-cased by mobile browser. In desktop browser when i type username it is abc_xyz but in mobile it is Abc_xyz which ends up server not finding user in DB.
Server code is poorly written to not handle case in-sensitivity of username and no proper handling of error conditions.
Lesson learned, take a close look at request body.

How to ping an IP address from a VueJS application?

Working on VueJS application, I want to create a function that pings a specific IP address and returns the time and status.
1- I used ping-lite but I got this error: Could not detect your ping binary..
I saw that in the node module they are checking the machine OS (running on Windows and WSL) and throwing that error if failing.
2- I then tried ping and I got this error:
(Promise/async): "TypeError: net.isIPv6 is not a function"
I was trying to executing the example code from their npm/github page:
var ping = require('ping');
var hosts = ['192.168.1.1', 'google.com', 'yahoo.com'];
for(let host of hosts){
let res = await ping.promise.probe(host);
console.log(res);
}
I wonder if the problems are related and if it's something with my environment/machine.
How to resolve this OR what's the best way to ping an IP address from a Vue app?
Ping is a node.js module not supported in the browser. This module would need to run server-side.
This could be accomplished us axios where you issue a GET call to the url and if you get a 200 back that indicates a successful call. This could also be accomplished using $ajax.
axios example
const response = await axios.get('https://api.github.com/users/mapbox');
if (response.status === 200) {
console.log('success'
}

Post request throws net::ERR_HTTP2_PROTOCOL_ERROR

I'm getting this 2 errors when using post request to an API
(Using chrome)
xhr.js:178 POST MY_API_URL net::ERR_HTTP2_PROTOCOL_ERROR
createError.js:16 Uncaught (in promise) Error: Network Error at
createError (createError.js:16) at XMLHttpRequest.handleError
(xhr.js:83)
I'm doing a simple POST request
(React code):
const postData = async()=>{
let res = await Axios.post('/terrenos', {'idTerreno':'0'} );
console.log( res.data );
}
And in the API side I just have this for debugging(PHP Code):
if( $_SERVER["REQUEST_METHOD"] === 'GET'){
main($_GET);
}else if( $_SERVER["REQUEST_METHOD"] === 'POST'){
echo(json_encode($_POST));
}
When I dont send anything in body it works just fine (It returns an empty array)
const postData = async()=>{
let res = await
Axios.post('https://gpgpy.000webhostapp.com/papaProject/API/v2/query.php');
console.log( res.data );
}
And when I use postman for the same request it with and without body it works too.
I ran into the same issue using Axios with React and a PHP web service hosted on 000webhost. It works perfectly fine with Postman as well as the vanilla fetch function. Odd, seems to be a compatibility issue between Axios and 000webhost...
My solution was to use fetch instead of Axios for my API calls, as I didn't see any particular reason to use Axios in my scenario.
Here's a good example on how to use fetch with POST.
Seems like you asked about it 3 months ago, so I hope you found a solution earlier than I could reply. If you managed to utilize Axios with 000webhost, please share your wisdom 😎

Making HTTP GET request from Chrome Extension

I have built a chrome extension and, at time of loading, I need to make a GET request to a server (trying it now from localhost).
Using Chrome debugger I can see that the call is made, but it is never received on the locahost server (which is running).
Javascript code:
$.get( "http://localhost:8080/myproject/api/getInfo", { userId: "me" } )
.done(function( data ) {
alert('Received!');
});
This is what I can see from Chrome debugger:
Request URL:http://localhost:8080/myproject/api/getInfo?userId=me
Request Headers
Provisional headers are shown
Accept:*/*
Origin:chrome-extension://ginkmpnhbepolafnopjackbgefh
Query String Parameters
view source
view URL encoded
userId:me
If I put http://localhost:8080/myproject/api/getInfo?userId=me directly on a browser it works well.
What is wrong?
I don't know what is problem in above code but same things I have done using below code via creating an AJAX XMLHttpRequest Object on chrome extension script.
var userid="me";
var xmlHttpRequest = (window.XMLHttpRequest) ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xmlHttpRequest.open("GET","http://localhost:8080/myproject/api/getInfo",true);
xmlHttpRequest.send("userid="+userid);
xmlHttpRequest.onreadystatechange = function()
{
if(xmlHttpRequest.readyState == XMLHttpRequest.DONE)
{
alert('Received!');
}
}
The problem I had was that the browser was blocking calls from the HTTPS site (where the plugin was displayed) to HTTP://localhost.
It started working when I deployed it to production with a HTTPS server URL.

Categories