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'
}
Related
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 ?
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).
I am trying to fetch food by its key. In postman api is working fine but is the forntend it has no response.
backend code
app.get('/foods/:key', (req, res) => {
foodsCollection.find({ key: req.params.key }).toArray((err, documents) => {
res.send(documents[0])
})
})
frontend code
const { key } = useParams()
const [foodById, setFoodById] = useState({})
useEffect(() => {
fetch(`http://localhost:5000/foods/${key}`)
.then((res) => res.json())
.then((data) => {
setFoodById(data)
})
}, [key])
Although you've added some images above, the most important is missing, namely, what are the Browser's Developer Tools stating the problem is. You should see some message in the Console tab, as well as in the Network tab for that particular request, if it is indeed being made. Until anyone sees this, it will be very difficult to help in fixing your problem.
If your not already, I suggest scaffolding any react app with create-react-app (CRA). This will give you a working app to start from. You can ignore CORS related issues in development, if using CRA, by adding "proxy": "http://localhost:5000", to your package.json file, see here for more on this method, but remember, this is only works for local development. You can also start Chrome to ignore Web Security by running it with the --disable-web-security flag e.g. chromium --disable-web-security, but that isn't a great idea really, more a way to quickly determine if you are having CORS problems, as Chrome masks some problems as CORS related, when in fact they aren't.
I'd also suggest changing your fetch code to use await, so instead you'd have:
const response = await fetch(`http://localhost:5000/foods/${key}`);
if (!response.ok) {
console.error(`Error message: ${response.statusText} ${response.status}`);
}
const result = response.json();
console.log(result);
This isn't necessary, but I've always found it way easier to read than the then/catch/finally method.
Reason for error
You need to stringify an object before sending it to the client with the JSON.stringify() method. When we exchange data to/from a web server, it must be a string.
Solution:
Proper way to send response to the client would to wrap the entire API in a try-catch block and explicitly specify the HTTP Status Code along with the stringified data in every response.
Note: Although 500 status code is used for error handling, you should choose one as per the use case.
app.get('/foods/:key', (req, res) => {
try {
/*
rest of the code
*/
foodsCollection.find({ key: req.params.key }).toArray((err, documents) => {
if (err) {
// 500 stands for internal server error
return res.status(500).send(JSON.stringify('Here goes a meaningful error message!'));
}
// 200 stands for success
res.status(200).send(JSON.stringify(documents[0]));
});
/*
rest of the code
*/
} catch (error) {
// 500 stands for internal server error
res.status(500).send(JSON.stringify('Here goes another meaningful error message!'));
}
})
The problem is that you haven't set the CORS headers of response in your backend code. and you are using different ports in your backend and frontend (5000 & 3000) so the Same Origin Policy disallows reading the remote resource, indicating that the request was blocked due to violating the CORS security rules.
you've to set the CORS headers.
you can install the CORS npm package and follow it's instructions to resolve the issue like this:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
.
.
.
And one other issue that I'm seeing is that you've put the react-router default route before your specified path. so move the <route path="*"> after <route path="/foods/:key">
I built an website in node js on the web side I manage to log in to the website using axios.
export const logInFnc = async (email,password)=>{
try{
const login = await axios({
method:"POST",
url:"/api/v1/user/login",
data:{
email:email,
password:password
}
});
if(login.data.status = "success"){
showAlert('success','You have successfully logged in!!!');
window.setTimeout(()=>{
location.assign('/global-post')
},1500)
}
}catch(err){
showAlert('error',`There was a problem,you probably forgot your password or your email address is no longer valid.=>${err}`);
}
}
In the browser it works without problems as well as in the postman,
but in the angular it gives me an error of 400 and does not recognize anything
I think you have a problem with the URL, probably you are running a development server for angular in a port like 3000 and you have the API running in another port. Ensure this.
If the API is running in another port, you should change your URL param to add hostname + port, something like http://localhost:{API_PORT}/api/v1/user/login
I actually think that you are missing some words in the URL. Just copy the URL of the request (that you are using in postman) and use it in your angular project. Or create an enviroment file to save it there, and just grab it whenever you want.
I was going to use PaperCut API though as far as I can judge XML-RPC doesn't support Node.JS or I couldn't find an appropriate client for the purpose. Here's the link with PaperCut API:
https://www.papercut.com/support/resources/manuals/ng-mf/common/topics/tools-web-services.html
I was wondering who had been able to get it working in JavaScript. I'm using Node.js in QNAP (in Container Station). If it can be run in Python should I install Python container? Could I use a snippet of code in Python requesting it from Node.js?
I work for PaperCut Software
Sorry it took me so long to reply to this, but I eventually found a free afternoon to knock up some code.
var xmlrpc = require('xmlrpc')
const authToken = 'token'
const hostAddress = "172.24.96.1"
// Waits briefly to give the XML-RPC server time to start up and start
// listening
setTimeout(function () {
// Creates an XML-RPC client. Passes the host information on where to
// make the XML-RPC calls.
var client = xmlrpc.createClient({ host: hostAddress, port: 9191, path: '/rpc/api/xmlrpc'})
// Sends a method call to the PaperCut MF/NG server
client.methodCall(`api.${process.argv[2]}`, [authToken].concat(process.argv.slice(3)), function (error, value) {
// Results of the method response
if (undefined === error || null === error) {
console.log(`Method response for \'${process.argv[2]}\': ${value}`)
}
else
{
console.log(`Error response for \'${process.argv[2]}\': ${error}`)
}
})
}, 1000)
To run this from the command line try something like
node main.js getUserProperty alec balance