VUE axios get API not found - python

I have an app Vue + Django. I try to send some data from vue to database using axios post method. Unfortunately console shows error:
GET http://localhost:8080/api/get_data/ 404 (Not Found)
And the same happend in python console:
Not Found: /get_data/
I have function get_data defined in my views and i added a path to urls:
path('get_data/', views.get_data)
In frontend it looks like this:
addNewData() {
axios.post("/api/get_data/", this.componentData.data).then(response => {
console.log("ok");
});
}
Did I missed something?

axios.post("/api/get_data/" - this URL is relative to "current". That's why it is trying ot access http://localhost:8080/... where 8080 is the port of VUE app. Whereas Django app is running by default on 8000.
You should use absolute URLs to access one app from another: to access Django app API from Vue app.
Use different config/env.var in your VUE app to refer to backend API in debug (localhost) and prod (domain name + http/https) modes, like:
axios.post(conf.BACKEND_URL + "/api/get_data/")
in your case, in debug mode it should be (expanded):
axios.post("http://localhost:8000/api/get_data/")

if you don't used webpack proxyTable deal with '/api' ,you should add the backend address

Related

React app can't reach to backend python application on localhost on same server

I have a public cloud VM which has public IP say 160.159.158.157 (this has a domain registered against it).
I have a Django application (backend) which is CORS-enabled and serves data through port 8080.
I have a React app running on the same VIM on a different port (3000), which is accessing the Django app and is supposed to produce a report.
The problem is that, when I use http://<domain-name>:8080/api/ or http://<public-ip>:8080/api/, my application is working fine,
but when I try to fetch data from localhost like http://localhost:8080/api/ or http://127.0.0.1:8080/api/, the React app fails to fetch data with the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080/api/. (Reason: CORS request did not succeed). Status code: (null).
Here's what I've tried:
axios.get(baseURL, { headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
}
but it didn't work. What should I do?
Looks like you've gotten confused where those headers need to be. You're setting them on the request to the backend, but they need to be set on the response from the backend. After all, it wouldn't be very good security if someone making a request could simply say "yeah, I'm ok, you should trust me".
The problem is going to be somewhere in your backend Django app, so double check the CORS config over there.

How to configure axios to request to particluar <domain_name>/<path> just by writing path without having to hardcode domain name every time

Hey guys I am doing a project that uses Python as a backend and React as a frontend. Everything works fine. After deploying to heroku I changed all my axios request URL to my domain name. But I realize if I change my domain name I have to change the axios URL in my react app everytime. I have used redux to do perform axios request for CRUDL and all types of authentication. I know this sounds stupid but is there a way to configure all the axios request to particular domain name by only giving path name every time it makes request? Thanks
setup axios defaults something like this:
axios.defaults.baseURL =
process.env.NODE_ENV === "production"
? process.env.REACT_APP_PROD_URL
: process.env.REACT_APP_DEV_URL;
then in your .env file
REACT_APP_PROD_URL="https://api.example.com"
REACT_APP_DEV_URL="http://localhost:8000"

How to contact flask-restful api from react native app?

i am new to backend dev. I try to developp a flask restful api. I followed the documentation and made the suggested minimal api, that is just returning a jsonified dict. With postman, curl and in the browser, no problem, the api is running and responds to my requests.
From my react native app however, i always get a Netwrok Error.
I tried lots of things:
- multiple IP addresses for the flask serveur
- differents ways to use axios
- different os : win10, ubuntu
- different endpoints : /, /api, /test
- different ways of writing the api (flask-restful class, flask app functions ...)
- manips from web documentations : dev mode of my device, chrome dev tools (port forwarding)
- i asked a react native developper to check my client-side code, nothing wrong according to him,
precisions :
- python code runs under a conda virtual env
- appli runs under node js and expo
- container folders of my app and my api are at the same level
- the flask server does not respond 404 or whatever, it does not respond at all, the error returned in react native is a network error
- depending on url, the network errors occurs immediately or after a 2 minutes delay
- flask shows requests and status when called by postman, curl, chrome, but does not react when i press my buttons from the react native app
Here is (one of) my python code:
from flask import (Flask, jsonify)
# from flask_restful import Resource, Api
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
#app.route("/api", methods=["GET"])
def get():
return jsonify(hello='bouh !')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)
and here is the clientside code:
import React, {Component} from 'react';
import { View, Button } from 'react-native';
import axios from 'axios';
import { sharedStyles } from '../../SHARED/_shared';
var url = "http://192.168.1.16:5000/api";
export default class PrevCommune extends Component {
constructor(props){
super(props);
this.navigation=this.props.navigation;
};
getAxios=()=>{
axios.get(`${url}`).then((response)=>{
console.log("succes axios :",response);
}).catch((error)=>{
console.log("fail axios :", error);
});
};
getFetch=()=>{
fetch(url).then((response)=>{
console.log("succes fetch :",response)
}).catch((error)=>{
console.log("fail fetch :",error)
})
}
render(){
return (
<View style={sharedStyles.mainContainer}>
<Button onPress={()=>this.getAxios()} title={"get axios"}></Button>
<Button onPress={()=>this.getFetch()} title={"get fetch"}></Button>
</View>
);
};
};
And the lines returned by requests:
fail axios : [Error: Network Error]
fail fetch : [TypeError: Network request failed]
I saw lots of tutos, videos, articles on flask api but i didn't find where i am wrong. Please tell me if you have any ideas ! I think both client and server codes are ok, the problem seems to be that my requests are blocked by something.
Solved : the probleme was my firewall ... thank you ricardo for the CORS doc =)
What worked for me was to change the IP address of localhost to my network IP in the api call in react native and then starting the flask application using the below command.
flask run --host=0.0.0.0

write a reverse proxy in node js to call the api in django

My frontend code is running in angular at node httpserver port 127.0.0.1:8081
My backend services runnning in python django framework at port 127.0.0.1:9000
While calling my backend servies from angular http methods throws cors exception
so i wrote a proxy controller in my node js
var http = require('http'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
http.createServer(function (req, res) {
// This simulates an operation that takes 500ms to execute
setTimeout(function () {
proxy.web(req, res, {
target: 'http://127.0.0.1:9000/dummy/'
});
}, 500);
}).listen(8080, "127.0.0.1");
to listen and bind at angular. i run as the node proxycontroller.js, results a another port no 127.0.0.1:8080
from proxy controller it calls my backend service and result json but from the angular js calling the proxy controller from the http.get() method results cors problem
please help to solve this problem.
Enable CORS in Django
Uses this third-party lib django-cors to do it.
You are getting CORS because you are making the call from your AngularJS app and its host is 127.0.0.1:8081, different from your Django app host 127.0.0.1:9000
The error said CORS is supported only for specific protocals like http:// etc. So you have to add http to that url. When you say, 127.0.0.1, the browser is unable to understand which protocol to use to access that url, should it be using http:// or data:// or chrome:// etc. So you've to explicitly say http://
You have to configure cors in the backend. The backend (the API server) much explcitly say a site is allowed using the http header I specified earlier. Otherwise, I can open your website, edit the frontend using chrome console and remove all the security stuff. It has the be in the backend.
as http://127.0.0.1:9000 from the front end angular app, dosent need to create proxy server to transfer the calls to backend service.

Specify URLS for CORS in Django app on Heroku

I have an app in Heroku running with Django.
Now I'm starting to develop a Phonegap app that I want to make work with my Heroku app.
I can't make it work because of CORS (Cross-origin resource sharing) protection. So I need to exclude some urls (not all app) to make my Phonegap app work.
I've tried installing django-cors-headers, but it doesn't seem to work.
To test it, I'm making a call to obtain a csrf_token.
I added this to my setting.py (and of course followed the guide, setting all to default):
CORS_URLS_REGEX = r'^register/.*$'
CORS_URLS_REGEX = r'^login/.*$'
CORS_URLS_REGEX = r'^getcsrf/.*$'
And this is the Ajax call I try to make:
get: function() {
$.getJSON("http://domain.herokuapp.com/getcsrf/",
{
tags: "jquery,javascript",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(item){
console.log(item);
});
});
}
But I get this marked in red as an error and an empty response field:
GET http://domain.herokuapp.com/getcsrf/?tags=jquery%2Cjavascript&tagmode=any&format=json 200 OK 206ms
There's no cross origin restrictions with phonegap, it's using a webview, not a web browser.
The only thing you have to do with phonegap/cordova is to be sure your server is whitelisted in config.xml.
In cordova 3.3/3.4, the default setting is <access origin="*" /> which should allow access to any url.

Categories

Resources