I am unable to track down this issue I am having attempting to send a FormData object (containing a file) to a Flask-RESTful application. On the ReactJS side i have the following code:
const updateAvatar = ({ target }) => {
if (target.value) {
let form = new FormData()
form.append("file", target.files[0])
fetch(`myurl/avatar`, {
credentials: "include",
method: "POST",
headers: { 'Content-Type':"application/x-www-form-urlencoded" },
body: form
})
.then(response => response.json())
.then(data => Do Something)
}
}
On the Flask side I have the following code:
def post(self,user):
if request.endpoint=="avatar":
print('I can see this message but I error out on the next line')
f=request.files["file"]
The f=request.files["file"] causes the server to return a 400 error. I thought this was straight forward but i'm a bit stuck here.
One other thing to mention: I am running in a local HTTPS environment using credentials.
Any help would be much appreciated.
Related
Hi i got a python fast api backend server.
#app.get("/getName")
async def getName() -> JSONResponse:
data_sniffer = DataSniffer()
data = json.dumps(data_sniffer.get_data())
print(data)
return JSONResponse(content=data,headers={'content-type':'application/json'})
this is the console output of data :{"first_name": "test"}
My Frontend Code looks like this
useEffect(() => {
async function query() {
const options = {
method: 'GET',
mode: 'no-cors',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application-json',
},
};
const res = await fetch('http://127.0.0.1:3000/getName', options);
console.log(res);
const data = await res.json();
console.log(data);
}
query();
});
but i get following error message SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
my network response looks like this:
"{"first_name": "test"}"
Has anyone a clue why fetch cant parse the json?
For anyone who has the same issue what worked for me is I moved my Backend folder to the root directory of my Frontend and removed the mode no-cors of the fetch request. I installed the no cors app and now it works. I think the mode no-cors broke my request.
I've setup my project, i.e. I have created a front-end in React, and a back-end in Flask.
In my front-end I call my back-end with a post method with the following code:
function POST(path, data) {
return fetch(`${fetchUrl}${path}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + RequestAccessToken(),
},
body: JSON.stringify(data)
}
)
}
Where RequestTokenAccess():
const { instance, accounts, inProgress } = useMsal();
const [accessToken, setAccessToken] = useState(null);
const name = accounts[0] && accounts[0].name;
function RequestAccessToken() {
const request = {
...loginRequest,
account: accounts[0]
};
instance.acquireTokenSilent(request).then((response) => {
setAccessToken(response.accessToken);
}).catch((e) => {
instance.acquireTokenPopup(request).then((response) => {
setAccessToken(response.accessToken);
});
});
}
And then just the following to actually make the call to the back-end:
const [data, setData] = useState()
function fetchData(e) {
e?.preventDefault();
POST('/my_app', { data: data }).then(
async (response) => {
const json = await response.json()
setData(json.return_data)
}
)
}
So for the front-end everything is working. I can get a MS Login that authorizes me so I can actually se the front-end, and I can also get a token from the RequestAccessToken function, which is given as a header to the back-end call. So everything seems to be set on the front-end part. However, the back-end calls also need to be secure is my guess, but I am not sure how that works.
Basically my app.py file looks something like:
from flask import Flask, request, jsonify
from my_app_func import MyAppFunc
app = Flask(__name__)
#app.post("/api/my_app")
def my_app():
data = request.json.get("data")
return_data = MyAppFunction(data)
return return_data
So basically, what do I need in order secure back-end calls ? I have the token as a Bearer Token in the post call. But what is the next step ? What do I actually do with it ?
I also have the same question, but couldn't find answer. Below is what works for me:
If you want to validate the user from flask, you can send the token along with your request from react.
Then within flask, validate the user by making a request to microsoft graph api.
Here is one example how to do this:
https://github.com/Azure-Samples/ms-identity-python-flask-webapp-call-graph
Another question for you is why you can directly concatenate RequestAccessToken() as a string? isn't it only call the setAccessToken? I ask because in my react app, I don't know how to export the token so that other function can use it. I ended up using the MSAL.js v2, not the one for react.
You have to register another app on the portal azure and and give permissions to the api and configure that in the another app in portal azure . Try to do something in that space.
Hi there I am doing a project with a React Frontend and Flask Backend. I am using axios to make calls from the Frontend to the Backend, but I am having trouble accessing the data I am sending with my request. I have tried several different methods of accessing the data but have no luck printing my variables.
Here is my flask endpoint:
#app.route('/login')
#cross_origin()
def login():
print(request.data)
return "Hello World"
Here is my axios call:
let options = {
method: 'GET',
url: flaskEndpoint+ "/login",
data: JSON.stringify(loginData),
// crossOrigin:'Access-Control-Allow-Origin',
crossOrigin:'*',
headers: {
'Content-Type': 'application/json'
},
json: true
}
console.log(JSON.stringify(loginData))
axios(options)
.then(response => {
console.log(response);
// this.setState({
//
// })
setAuth(true);
Cookies.set("user", "loginTrue");
})
.catch(error => {
console.log("Error in the axios call:" + error);
})
}
And here is the result in the flask terminal:
What am I doing wrong and is there a better way?
So I should have used "print(request.json)" instead. Then I could access the data being sent, or use "request.json.get('username')" to get a particular value.
I'm developing a React Native app. As a backend I'm using DJango DRF. I'm trying to make POST request for creating a new element on backend, this is my code in React:
**API.JS**
const routes = {
accounts: {
get: () =>
requestHelper({
method: "get",
url: "accounts/",
}),
post: (data) =>
requestHelper({
data,
method: "post",
url: "accounts/",
}),
},
};
**API CALL**
const formData = new FormData();
const image = {
uri: data.image,
name: data.timestamp + ".jpg",
type: "image/jpeg",
};
_.map(data, (item, name) => {
formData.append(name, item);
});
formData.append("image", image);
await api.accounts
.post(formData)
.then((res) => {
console.log(res, "OK");
})
.catch((err) => {
console.log(err);
});
};
Te request is reaching backend and the new Account is being created on database (including the image). The problem is that,despite that Django is returning 200_OK, the api call is going to the catch statement, and this error appears on console:
Network Error
Stack trace: node_modules/axios/lib/core/createError.js:15:0 in
node_modules/axios/lib/adapters/xhr.js:81:4 in
dispatchXhrRequest
node_modules/event-target-shim/dist/event-target-shim.js:818:20 in
EventTarget.prototype.dispatchEvent
node_modules/react-native/Libraries/Network/XMLHttpRequest.js:575:10
in setReadyState
node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in
__didCompleteResponse node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10
in emit
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19
in __callFunction
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6
in __guard$argument_0
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10
in __guard
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4
in callFunctionReturnFlushedQueue [native code]:null in
callFunctionReturnFlushedQueue
I think is not an Image problem, because I've removed for testing and same error appears.
Usually, you get the Network Error when the REST API server can't be reached. Have you set the correct baseURL or proxy to the Django server? Django server is probably running on 8000 and React is running by default on 3000.
The fact that you see a request on the server-side is a little strange. It will suggest that there might be a bug/problem in the code that is used to process a successful response. Have you tried to remove that code? Yes, might sound strange, just remove the console.log(res, "OK"); and see what will happen?
I've got an app on Google App Engine for which I use the webapp2 authentication as described in this tutorial (thus Google Account API is not being used for user account management).
Therefore I'm using this Google tutorial to implement Google+ Sign-In. The front-end works fine, however I am having troubles with the callback. I would like to do this without Flask, since the only thing it seems to be used for is generating a response. The original code for the first part of the callback is:
if request.args.get('state', '') != session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
To get rid of the Flask dependency, I rewrote this to:
if self.request.get('state') != self.session.get('state'):
msg = json.dumps('Invalid state parameter.')
self.response.headers["Content-Type"] = 'application/json'
self.response.set_status(401)
return self.response.out.write(msg)
The problem though, is that self.request.get('state') returns nothing. I'm guessing this is because I am not reading the response properly, however I don't know how to do it right.
The Javascript that launches the callback is:
function signInCallback(authResult) {
if (authResult['code']) {
// Send the code to the server
$.ajax({
type: 'POST',
url: '/signup/gauth',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
console.log(result),
processData: false,
data: authResult['code']
});
} else if (authResult['error']) {
// There was an error.
// Possible error codes:
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatially log in the user
console.log('There was an error: ' + authResult['error']);
}
}