calling axios in vue get Network Error - python-3.x

I working on one small project. Server side realized on Python as RESTFul server. Front-end I try do with Vue. I'm new in Vue. And when I try to fetch data fro service I get Error: Network Error. And I can't found mistake.
Irony is that I see fetched data in browser in network->Response tab. But not on HTML page. On the page I see Error: Network Error only.
I can fetch data with browser directly, by url.
I can fetch data with CURL
Also I can fetch data with this Vue code from third-part services! But not from local URL.
FLASK SERVER CODE
#app.route('/', methods=['GET'])
def get_data_list():
return 'Test'
VUE code
var app = new Vue({
el: '#app',
data: {
data_list: '...',
url_A: "#home",
url_B: '#page2',
url_C: '#settings'
},
created: function () {
this.loadData()
},
methods:
{
loadData: function () {
this.data_list = "Loading...."
var app = this
axios.get('http://127.0.0.1:5000/')
.then(function (response) {
app.data_list = response.data[0]
})
.catch(function (error) {
app.data_list = "An error occurred. "+error+" / Error ststus: "+error.response
})
}
}
})
I'm a little bit confused. What is wrong with my code?

You have mentioned that you are getting this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 127.0.0.1:5000. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
This means you have a CORS (Cross Origin Resource Sharing). Which means you are trying to send and/or receive request from two different domains/ports.
So, for example if you send a GET request from localhost:8080 to localhost:5000 you'll get the same error, because you are trying to share resources across different origins:
So, one way to fix this problem is to instruct your back-end server (127.0.0.1:5000) which I assume is running a flask app to allow you to send it a GET request from (127.0.0.1:8080).
So, configure your flask app with this CORS guide http://flask-cors.readthedocs.io/en/latest/

Related

(Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 204

I am trying to download a PDF from my backend. and i am getting this error.
Blockquote
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.115:5000/journal/download/HP-protein-prediction.pdf-1641052987115.pdf. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 204
Blockquote
I have enabled cors and tried a million things but it's not working.
Here's my code
Enabling Cors Code
Browser response
and finally my server side and frontend code
Server Side
Frontend request using Axios
My Logged Error :
Logging error Error: Network Error
createError createError.js:16
handleError xhr.js:117
dispatchXhrRequest xhr.js:114
xhrAdapter xhr.js:15
dispatchRequest dispatchRequest.js:58
request Axios.js:108
method Axios.js:129
wrap bind.js:9
downloadJournal apiCalls.js:64
onClick ViewArticle.js:23
React 14
unstable_runWithPriority scheduler.development.js:468
React 15
js index.js:9
js main.chunk.js:14047
Webpack 7
So as far as I can understand you are trying to download a pdf file in the frontend whenever you hit some API in the backend that sends the pdf to the frontend. I haven't tried the same with the Axios library but you can try using a normal fetch command
For Frontend
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
})
.then((response) =>
response.blob()
)
.then((blob) => {
console.log(blob)
// Create blob link to download
const url = window.URL.createObjectURL(
new Blob([blob]),
);
const link = document.createElement('a');
link.href = url;
link.setAttribute(
'download',
`${e.target.value}.pdf`,
);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
// Clean up and remove the link
link.parentNode.removeChild(link);
});
For Backend, I was using Nodejs which has a library file-system or fs
var file = await fs.readFileSync(`location-to-pdf/${req.body.fileId}.pdf`)
res.contentType("application/pdf");
res.send(file)
As of my experience if we use app.use(cors()) without specifying any configuration it works without any problem
The only doubt I had was about the URL of the API why is that not localhost whereas it's 192.168... if your app is running on localhost maybe you can send it directly to it without the rerouting
Major browsers its CORS policies prohibit this action, You CANNOT download any data from another domain/ip not the same of your frontend script domain/ip address.
Backend & Frontend must be exist in the same domain.
For development purpose, you can overcome this limitation by creating new shortcut with this target:
"[Path to Your Chrome]\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp

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

ReactJS - NodeJS - Issue Connecting to Graphql On AWS Lambda

I have a nodejs lambda function deployed on aws which exposes a lambda endpoint via API Gateway.
The endpoint is here and allows you to access the graphiql endpoint.
I have been trying to call this from my react code but I am getting the following error response
{"message":"Missing Authentication Token"}
And the following console warning
Failed to load https://z8zch5bp3m.execute-api.us-east-1.amazonaws.com/test: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have enabled cors in the API gateway but still getting this error.
My simple react code is as follows
import React, { Component } from 'react';
import { gql } from 'apollo-boost';
import { Query } from 'react-apollo';
const ADD_NUMBERS = gql`
query {
addNumbers(number1:1, number2:55) {
add
}
}
`
const App = () => (
<Query query={ADD_NUMBERS}>
{({ loading, error, data }) => {
if (loading) return <div>Loading...</div>;
if (error) return <div>Error :(</div>;
return (
<div>Data: {data}</div>
)
}}
</Query>
)
export default App;
The nodejs code for my lambda function is located here
Please let me know if I need to do anything to get this lambda call working.
Looking into your code did not tell me much. I would advise you to take a look into those topics:
Missing Authentication Token is also returned when you make an HTTP call with the wrong method (say you want to POST, but you PUT);
Look into Lambda Proxy Integration. When using Lambda Proxy Integration you can specify headers in your response. There you can make sure to allow Cross-Origin-Resource-Sharing.
Hope this helps.
Got this working by recreating my api gateway endpoints with cors enabled from the start and it worked as expected

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am using nodejs server, express framework and fetch library to send request to another server which is in different domain. For one of my endpoint consider (localhost:8080/login) i am rendering ejs file when the user clicks login button i am sending a fetch request to an api (https:otherserver.com/login) different server which is in other domain. i am not able to send this request. I am getting this error :
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am not sure how to handle this issue. please suggest some ideas or links which can solve this issue.
You can use cors middleware on your server.
Simplest way to use it is to add :
app.use(cors())
before all of your route handlers.
I found the solution for my problem. I am trying to explain what i understood as i am a beginner in server side and web development.
This was the problem i faced :
For one of my endpoint in my nodejs server, consider (localhost:8080/login) i am rendering ejs file when the user clicks login button in that ejs file, i am sending a fetch request to an api (https:otherserver.com/signin) of different server which is in other domain. i am not able to send this request. I was getting cors problem.
Cors problem was occuring because the server domain(my nodejs server) which rendered the ejs file and the other domain(https:otherserver.com/signin) to which i was making fetch request after clicking login button was different.
so solution was :
I need to make the fetch request first to the same domain(my nodejs server localhost:8080/api/signin). And then from this server i should call the api of other domain(https:otherserver.com/signin). By doing this we wont get any cors issue. Because the client side ejs file is requesting to the same server which has rendered the file. And then the server is bypassing the request to the other server.
code from client side javascript file. /api/signin is an endpoint in my local nodejs server and u can add the options:
options ={
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
body : JSON.stringify({
email_address : emailId,
password : pwd
})
};
fetch("/api/signin",options)
.then(function(res) {
console.log(res);
}).catch(function(error) {
console.log(error);
});
code from local nodejs server side:
express.use('/api/', function (req, res, next) {
var options = {
method : req.method,
headers :req.headers,
body : JSON.stringify(req.body)
};
fetch('https://otherserver.com'+req.path,options)
.then(response => {
return response.json();
}, error => { console.error(error)})
.then(function(json){
res.send(json);
})
.catch(function(error) {
res.send(error);
});
})
Hope this may help someone who is beginner in server development.

request to nodejs proxy: Provisional headers are shown

In my web app project, I came across a cross domain issue. The back-end API was deployed to the server, which providing the IP and port(We can assume the back-end API works well). And I am working on the front-end side, and still in the local development stage. So there is cross domain issue.
so I used a nodejs proxy and try to overcome the cross domain issue. For the nodejs proxy part, I am not the expert on that. Just get it from my teammates, who meet the same issue before.
So in my client side js code, I use axios library to send http request to the nodejs proxy as following:
axios.get('http://127.0.0.1:8888/service/delete/v1?id=5').then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
And the nodejs proxy will replace the 127.0.0.1:8888 part with the real API's IP and port, and send the request. That's my understanding about it.
so I run the nodejs proxy, which is listening on port 8888, and run my frond-end code in another console. But when I send the above mentioned request. I got the error as following:
GET http://127.0.0.1:8888/service/delete/v1?id=5 net::ERR_CONNECTION_TIMED_OUT
Error: Network Error
at createError (createError.js?f777:16)
at XMLHttpRequest.handleError (xhr.js?14ed:87)
and I debug the error deeper in the chrome devtool, and find the Provisional headers are shown in the header as following
I searched some previous article about this issue.It's said that the potential reason is the request is blocked.
But I can send other HTTP request successfully to other third party APIs. For example my mock data service Mockarro as following:
const key = 'mykeyxxx';
const url = `http://www.mockaroo.com/api/generate.json?schema=firstapis&key=${key}`;
axios.get(url).then((response) => {
console.log(response);
});
So my the previous request is blocked. I am very confused. My guess is the issue is from the nodejs proxy part? Right?

Resources