Why Can't I Fetch a Webpage (With NodeJS and Node-Fetch)? - node.js

I am trying to fetch a site: link here. If you click on the link, it shows JSON: {"error":"Socket Error"}. I am trying to fetch that website, and return the error.
However, I get a 403 Forbidden error instead. Is there a reason for this? I turned CORS off, but I don't think it did anything. Here is an example of what I have tried:
async function b(){
error = await fetch('https://matchmaker.krunker.io/seek-game?hostname=krunker.io&region=us-ca-sv&game=SV%3A4jve9&autoChangeGame=false&validationToken=QR6beUGVKUKkzwIsKhbKXyaJaZtKmPN8Rwgykea5l5FkES04b6h1RHuBkaUMFnu%2B&dataQuery=%7B%7D', {mode:'no-cors'}).then(res=>res.json())
console.log(JSON.stringify(error))
}
b()
Why doesn't anything seem to work?
Please comment if there is anything I need to add, this is my first Stack Overflow post so I am still slightly confused by what makes a good question. Thanks for helping!!
NOTE: My environment is Node.JS (testing on Repl.it which I think uses the latest Node version).

This particular host is protected width Cloudflare anti DDoS protection. The server doesn't accept requests made by fetch, but the do accept requests from curl. God knows why.
$ curl 'https://matchmaker.krunker.io/seek-game?hostname=krunker.io&region=us-ca-sv&game=SV%3A4jve9&autoChangeGame=false&validationToken=QR6beUGVKUKkzwIsKhbKXyaJaZtKmPN8Rwgykea5l5FkES04b6h1RHuBkaUMFnu%2B&dataQuery=%7B%7D'
// => {"error":"Socket Error"}
You can use curl in node.js with node-libcurl package.
const { curly } = require('node-libcurl')
const url = 'https://matchmaker.krunker.io/seek-game?hostname=krunker.io&region=us-ca-sv&game=SV%3A4jve9&autoChangeGame=false&validationToken=QR6beUGVKUKkzwIsKhbKXyaJaZtKmPN8Rwgykea5l5FkES04b6h1RHuBkaUMFnu%2B&dataQuery=%7B%7D'
curly.get(url)
.then(({ statusCode, data }) => console.log(statusCode, data))
// => 400 { error: 'Socket Error' }
Works as expected :-)

You can use a proxy such as allorigins.win which is a cors proxy that can retrieve the data from a URL in the form of json. You can fetch from this URL: https://api.allorigins.win/raw?url=https://matchmaker.krunker.io/game-list?hostname=krunker.io

Related

Page not changing onClick using useNavigate in React?

I have a very basic UI for a login page:
Upon clicking the LOGIN button, the following methods gets called:
async function loginPatient(){
let item ={username:userName, password};
let result = await fetch("http://localhost:8000/users/login",{
method:'POST',
headers:{
"Content-Type":"application/json",
"Accept":"application/json"
},
body: JSON.stringify(item)
});
alert(result);
alert("breakpoint")
result = await result.json();
localStorage.setItem("user-info",JSON.stringify(result));
nav('/patient')
}
At this point I simply want it to change the page when the button is clicked. My API returns the following information from the database:
To test I did console.log("hello world") in the first line of the function and it works
However, If I run console.log("hello world") after the let result = await fetch(...) part it does not work. How can I test this to see why it's not working ?
Here are the errors from the console:
I did not write the API and do not know how Node works yet, I am just doing the front end for this
The issue is code is never reaching after fetch line, basically request is failing, the error on console is saying the due to CORS issue, the request failed, and in your loginPatient function, you have not handled the failed case, if you just wrap your fetch call inside try/catch block, you will see your code will fall into fail block, as api failed.
You need to enable CORS on your server or backend, Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
You can read more about cors at:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Looks like your client is on some other domain or port(if your are developing locally) than your server. You need to enable CORS permission for your client url.
And if you are using express for your backend, you can check the following url to enable cors.
https://expressjs.com/en/resources/middleware/cors.html
And last thing why Postman is getting success response, because it is by passing this cors check, as Postman is making request from it's server to your direct server instead of browser.
First initialize you navigation variable as follows
const navigate =useNavigate()
then navigate to you specific route by returning you navigation variable as follows.
return navigation("/");
Happy Coding!

How to do a get request with parameters [NODE.JS]

Thank you for reading. It has litteraly been hours that i've been searching for my problem: as said in the title didn't found anything even looked at docs of nodejs but there isn't what i'm searching so it's weird seems like no one does that?
const https = require("https")
https.request("http://aratools.com/dict-service?query=%7B%22dictionary%22%3A%22AR-EN-WORD-DICTIONARY%22%2C%22word%22%3A%22%D9%86%D8%B9%D9%85%22%2C%22dfilter%22%3Atrue%7D&format=json&_=1643219263345",
(res) => {
console.log(res)
}
)
the error:
enter image description here
website used: http://aratools.com/
Trying to do experiment thing later on (have something in head but first have to manage to do this get request)
You need to specify https in the URL and not http if you're using the package https. Otherwise you should use the package http.
Use the http module instead of https.
const http = require("http")
http.request("http://aratools.com/dict-service?query=%7B%22dictionary%22%3A%22AR-EN-WORD-DICTIONARY%22%2C%22word%22%3A%22%D9%86%D8%B9%D9%85%22%2C%22dfilter%22%3Atrue%7D&format=json&_=1643219263345", (res) => {
console.log(res)
});

VueJS axios.get returns Error: Request failed with status code 404

I've been debugging this code for a while, without much luck:
async getEvents() {
try {
let response = await axios.get("http://localhost:8000/events/");
console.log(response);
return response.data;
} catch (error) {
console.error(error);
}
}
The complete code sample is from: https://auth0.com/blog/how-to-make-secure-http-requests-with-vue-and-express/
I receive an error when visiting the site that calls the API endpoint:
Error: Request failed with status code 404
at createAxiosError (utils.js?c786:148)
at Object.settle (utils.js?c786:127)
at handleRequest (handle_request.js?da0c:126)
at eval (index.js?94db:26)
at new Promise (<anonymous>)
at MockAdapter.eval (index.js?94db:25)
at dispatchRequest (dispatchRequest.js?5270:52)
If I just copy the url (http://localhost:8000/events/) in the browser I receive the correct data. I have tried with and without trailing slashes.
Am I misunderstanding the error message, and should I look elsewhere?
In computer network communications, the error 404 indicates that the browser was able to communicate with a given server, but the server could not find what was requested, in other words, the request url did not exist. So you want to double-check that.
Solution: Go to the network tab, click on the error request, inside the Headers, you can see the actual request url which has been sent to the server.
A 404 usually indicates that the resources was not found. Have you added any previous setup to your Axios instances? like the baseURL?
Most of the time the BaseURL is set to on an Axios instance that can cause confusion and issues.
I Had the same issue, then just added in my catch(vuex) error.response

"Cross Origin Request Blocked" No solutions seem to work

Background
I'm building a MERN full stack application as a personal project. I am running the frontend client on localhost:3000 and the server on localhost:5000.
Problem
All of my API routes work as expected except for a GET request, router.get('/get-friends', ...) which queries the mongoDB to return a list of collection documents. Calling that get request on Postman returns the expected output. I decided to write a simple GET request that returns a method and it works just fine in my browser
When making the request the get-friends request in my browser, I get the following log:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/users/get-friends/. (Reason: CORS request did not succeed)
What I've Already Tried
Enabling cors in my Express server
Enabling cors preflight
Adding a proxy to the server from the client's package.json
Switching from Axios to vanilla JS's fetch() method
Turning off cors in my browser
I suspect the issue occurs when I make the request to the database from Express. I am really not sure how to solve this issue.
Here is the route in question:
router.get('/get-friends', (req, res) =>{
var species_ = req.body.species;
var gender_ = req.body.gender;
var neutered_ = req.body.neutered;
// query db
Friend.find({species: species_},{gender:gender_},{neutered:neutered_}).then((friends_) =>{
if(!friends_){
return res.status(404).send('query error, nothing returned');
}
return res.send(friends_);
}).catch((e) =>{
res.status(400).send(4);
})
});
Here is the project repo and the relevant files are:
https://github.com/edgarvi/foster-friends/server.js (Express server)
https://github.com/EdgarVi/foster-friends/blob/master/routes/api/users.js (Routes for the express server)
https://github.com/EdgarVi/foster-friends/blob/master/client/src/components/layout/SearchFriends.js (React component which calls the server)
I would gladly appreciate any help!
I have highlighted possible problems.
Reason: CORS request did not succeed
The HTTP request which makes use of CORS failed because the HTTP
connection failed at either the network or protocol level. The error
is not directly related to CORS, but is a fundamental network error of
some kind.
> In many cases, it is caused by a browser plugin (e.g. an ad blocker or
privacy protector) blocking the request.
Other possible causes include:
Trying to access an https resource that has an invalid certificate
will cause this error.
Trying to access an http resource from a page with an https origin
will also cause this error.
As of Firefox 68, https pages are not permitted to access
http://localhost, although this may be changed by Bug 1488740.
> The server did not respond to the actual request (even if it responded
to the Preflight request). One scenario might be an HTTP service being
developed that panicked without returning any data.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed
Thank you all for the help and the suggestions. After struggling through this for multiple days, I finally encountered a solution.
In my react client, I made the API call:
axios.get('http://localhost:5000/api/users/get-friends',
{
params: {
species: this.state.species,
gender: this.state.gender,
neutured: neutered_
}}
);
and then I changed the Mongoose query to look like:
router.get('/get-friends', (req, res) =>{
var species_ = req.query.species;
var gender_ = req.query.gender;
var neutered_ = req.query.neutered;
// query db
Friend.find({species: species_},{gender:gender_},{neutered:neutered_}).then((_friends) => {
return res.send(_friends);
})
});
I'm not exactly sure why these changes made my code finally work but once again, thank you all for the help and suggestions!

How to enable POST method on heroku server (for React app)? I am getting 405 method not allowed

I am getting 405 method not allowed. I am using axios.post for login.
The form is taking input username and password and post to get authenticate.
But POST method not allowed at heroku error in console.
Please help me to let me know how to enable POST method on heroku. or any solution.
Thanks in advanceenter image description here
This is an axios post example:
axios.post("test/test", {userName:'..', password:'..'}).then((result) => onSuccess(result.data), (error) => onError(error));
If you are using spring-boot with Java you probably have a CORS problem. Try to put in your endpoint:
#CrossOrigin(origins = {"http://localhost:3000", "url2", "url3})
Replace "http://localhost:3000" with your localhost url if you need it. This is an example:
#CrossOrigin(origins = {"http://localhost:3000", "url2", "url3})
#RequestMapping(value = "/test", method = RequestMethod.POST)
ResponseEntity<HttpStatus> testLoginUser(#RequestBody DTO testDto) throws TestException {
//Do Something..
}
I don't know how the server is implemented, so: check if you have a CrossOrigin problem or if you have a security problem with your endpoints.

Resources