I was wondering if someone could bring some light on how GET request paths work. I am not skilled in networking so am a bit lost here.
I have a Flask app running on PythonAnywhere... I built a small app with Vue and am using Axios for send GET request to my API on server. I however found out that when I run my app on PythonAnywhere server i will get response only when I also run the flask app on my local machine. I suspect it is due to me trying to send the request to http://localhost:5000/api/random2. Is that true? What do I have to replace it with to send the request to my PythonAnywhere app?
getResults () {
const path = `http://localhost:5000/api/random2`
axios.get(path, {
params: {
p_a: this.p_a,
R_eH: this.R_eH,
a: this.a,
b: this.b
}
})
.then(response => {this.result = response.data})
.catch(error => {
console.log(error)
})
}
},
Thank you,
Jakub
Related
I have 2 amplify webapps and I want that both are using the same AWS backend. So i followed the instructions on https://docs.amplify.aws/cli/teams/multi-frontend/#workflow. App A has the full amplify backend src and App B shall use these too. So I run on App B.
amplify pull
>Amplify AppID found: df4xxxxxxx. Amplify App name is: XXXXX
>Backend environment dev found in Amplify Console app: XXXXX
Seems to work.
But when I now try to make an api call via:
AWS_API = 'api_name_on_aws';
async getUserInfosByUsername(username) {
var userInfos;
await API.get(this.AWS_API, `/users/infos/testuser`,
{
headers: {},
response: true,
body: {},
queryStringParameters: {},
})
.then((response) => {
userInfos = response;
})
.catch((error) => {
console.log(error.response);
});
return userInfos;
}
then no api request will send. (I can see within the google chrome dev console/network that no request is send).
The "request" method is just return "undefined" and thats all... On App A everything is working fine.
Did I miss something? Should I do something else that App B can use the API of APP A?
When trying to upload a selected image from my React Native project I get a nondescript error message:
Network request failed
Seems to be a common issue, but most people are just forgetting their file types or are on Android and have an issue with Flipper. Nothing that has worked for anyone I've found with the same symptoms has worked for me.
Code:
const localUri = result.uri;
const filename = localUri.split("/").pop();
const type = mime.lookup(localUri) || "image";
const formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
try {
const file = await fetch(`${SERVER_URL}/api/upload`, {
method: "POST",
body: formData,
}).then((res) => {
console.log(res);
return res.status === 200 ? res.text() : res.json();
});
} catch (e) {
console.log(e);
}
Considerations:
Using a physical IOS device. Iphone.
Using Expo 40.0.0 with corresponding RN SDK, not ejected.
Using expo-image-picker to get image.
Using NGROK to get requests through to my localhost server from my phone.
All other requests to my server from React Native work fine, it's only when I try to uplaod a file
Image renders fine from supplied URI, so it's getting the right source.
Form Data source from above:
{ "name": "CAPS-FILE-NAME.jpg", "type": "image/jpeg", "uri": "file:///var/mobile/Containers/Data/Application/CAPS-PATHING/Library/Caches/ExponentExperienceData/project-src-pathing/ImagePicker/CAPS-FILE-NAME.jpg", }
Things tried:
Using Content-Type header: "multipart/form-data"
Using /private instead of file://
Using Postman to hit my server through NGROK, which works
Changing my Expo/RN to 38.0.0
Getting base64 -> blob -> formData, same result
Many other things I've forgotten now. If it's on Google results, I've tried it.
For anyone who gets stuck with this also, I switched to using XMLHttpRequest instead of fetch and it miraculously works now. Not sure why fetch is broken in RN, but at least there's a solution.
I'm trying to fetch data in my React app from an Django server with Django Rest Framework, I'm using the built in token authentication.
componentDidMount() {
let headers = {
"content-type": "application/json",
"authorization": "Token <token is here>"
};
fetch('http://localhost:8000/api/stats/', {
headers: headers,
})
.then(res => res.json())
.then((data) => {
this.setState({ games: data })
})
.catch(console.log)
}
Inspecting the page in Chrome reveals this
This looks like two separate requests but I'm not sure.
The requests that has status (failed) has the headers I provided in React with in it. This request seems to have failed completely, it did not even reach the server.
The other request that has the status 401 doesn't have the headers I provided. The request did however get a response from the server.
Anyone have an idea what's wrong?
Solved by David Nováks comment:
Installed django-cors-headers in my django project.
Added my React servers hosting address to CORS_ORIGIN_WHITELIST.
My setup is running on Docker with a frontend (React) as well as a backend (Django) container.
I'm using the login-form component of the drf-react-app below in another project and am clueless as to how the api fetch request in the loginUser action creator (src/actions/user.js) knows which URL it is supposed to use..?
user.js:22 POST http://localhost:3000/api/obtain-auth-token/ 404 (Not Found)
I want it to send the request to the server at port 8000. I took the code from this drf-react boilerplate: https://github.com/moritz91/drf-react-login
export function loginUser(username, password) {
return (dispatch, getState) => {
const payload = {username, password};
dispatch({type: LOGIN_USER_REQUEST, payload});
return fetch(`/api/obtain-auth-token/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
})
.then(handleResponse(dispatch, LOGIN_USER_RESPONSE))
.then((json) => {
saveUser(json);
return json;
})
.catch(handleError(dispatch, LOGIN_USER_RESPONSE))
}
}
What am I missing?
In your package.json you have a proxy property set to "http://backend:8000". The proxy is used to redirect requests to a given url when you make a request against your local server http://localhost:3000. So if that's not working then you might be missing a step that enables the proxy.
I have just started learning React Native. Built my Component and am trying to use an authenticate function written in a separate file to authenticate.
My Authenticate file looks like
var constants = require("../constants")
module.exports = function(usr,pwd){
var trailing_url = '/api/token/';
var url = constants.DOMAIN + trailing_url;
console.log("url");
return fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: usr,
password: pwd,
})
}).then(function(response){
return response.json();
}).then(function(json){
return json;
});
}
I am experiencing this error once i go to fetch. I am unable to make network requests to my backend in django which is running at http://127.0.0.1:8000/api/token/
I am getting the following error. Couldn't copy paste that here for some reason.
Another question I had is how to debug the code? I tried the Chrome debugger.
But its showing
Status: Waiting, press Ctrl R in simulator to reload and connect.
Tried refreshing the Simulator but didn't work.
Thanks Ashutosh for pointing that out. I didn't notice that since the emulator is a different machine, it wouldn't actually recognize localhost or 127.0.0.1
The problem was i was using the local machine's Loopback IP Address when requesting for data.