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

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

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!

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

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

Browser not showing Internal Server Error HTML Page with status 500

I've two components in my application. A frontend which is built on Angular and backend built using express. I'm using the Nest.js framework in the backend.
I have an http-exception.filter.ts file which takes care of any thrown exception. So far, I've been handling Internal Server Error in the application this way.
if(exception.getStatus() === 500) {
response
.status(500)
.json({
status: '500',
code: 'INTERNAL_SERVER_ERROR',
message: 'Internal Server Error'
});
}
But, now an HTML page has been designed showing Internal Server Error message. All I need to do to render that page is to hit the URL /ui/internal-server-error. So, I tried to that using the code below.
response
.status(500)
.redirect('/ui/internal-server-error');
The page loads when a case of internal server error occurs, but the problem is I'm not getting 500 status when I'm reading the network logs in the browser. Instead, I'm getting 304 Not modified status.
Could anyone please point me in the right direction? I want to show the error page along with status code 500 and the UI page needs to come from Frontend only as I've no access over it.
When redirect is called, it sets the status, so the 500 is replaced.
From the express docs (relevant as NestJS uses Express by default):
Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.
res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')
Add the desired status as an argument to redirect.

"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!

Accessing QCMobile API

I'm currently tasked with accessing data from the Department of Transportations QCMobile API, located here.
I've made an account and have obtained my key. I've tried accessing it through Ajax calls, Node's Request and https modules, and now I'm just trying to get a response via Curl.
Every time I try to access it I get the same error: error 403, Forbidden.
My URL appears to be properly formed, as seen here:
https://mobile.fmcsa.dot.gov/qc/services/carriers/44110/basics?webKey=xxxx
When I run it from Node or from an Ajax call, I only get 403, Forbidden.
Here is my relevant Node code:
this.url = 'https://mobile.fmcsa.dot.gov/qc/services/carriers/' + dotNumber + '/basics' + '?webKey=' + this.webkey;
this.options = {
method: 'GET',
uri: this.url,
};
this.getDoTData = function() {
request(this.options)
.then(function (response) {
// Request was successful, use the response object at will
console.log(response);
})
.catch(function (err) {
// Something bad happened, handle the error
console.log(err);
});
}
When I run it via Curl, I get the same 403 with some extra detail:
curl: (56) SSLRead() return error -9806
I was wondering if anyone has any ideas as to if I'm accessing this API incorrectly. There doesn't appear to be much documentation, and the page on their site where you can submit technical questions seems to be broken.
Thanks for any insight.
This web service seems to be down for the time being. These problems started during the maintenance window on weekend of Nov 18th, and it has been in varying degrees of non-operation since then.
This is the response I got from FMCSA customer support today:
I do apologize about the inconvenience however, we have been experiencing technical difficulties with the App for a few weeks now. Our IT department is currently working on it however, at this time I do not have an exact time on when it will be fixed.

Resources