axios Post request returns null response - django

I am facing an issue of receiving NULL response for the axios POST request I made. How do I correct this error?
I've tried to changing multipart/form-data into x-www-form-urlencoded and multipart/x-www-form-urlencoded
async submitUser() {
this.memberObj = {
id: this.memberObjLocal.id,
name: this.memberObjLocal.name,
password: this.memberObjLocal.password,
email: this.memberObjLocal.email,
password: this.memberObjLocal.password,
gender: this.memberObjLocal.gender,
experience: this.memberObjLocal.experience,
birth: this.memberObjLocal.birth,
phoneNum: this.memberObjLocal.phoneNum,
address: this.address,
introduce: this.introduce,
pic: this.pic
};
const config = {
headers: { "Content-Type": "multipart/form-data" }
};
var formData = new FormData();
for (let data in this.memberObj) {
console.log(data);
formData.append(data, this.memberObj[data]);
console.log(this.memberObj[data]);
}
for (var key of formData.entries()) {
console.log(key[0] + ", " + key[1]);
}
try {
let response = await this.$axios.$post("/users/", formData, config);
this.$router.push("/");
console.log(response) // null
} catch (e) {
console.log(e.response);
}
}

Please try to use like this
import axios from "axios";
//... your codes here
axios({
url: "/users/",
method: "post",
data: formData,
headers: config.headers
})
.then(response => {
this.$router.push("/");
console.log(response);
})
.catch(error => console.error(error));
//... and other codes here
and you can see more examples!

Related

AWS post request works on postman but not react-native

This is my JS code for the API
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user:user
}),
})
.then((res) => {
return res.json();
})
.catch((err) => {
console.log("Error in getUser: " + err);
});
return json;
};
Here is an attempt to make the request, which unfortunately return the authentication error.
fetchUser.request("kirolosM")
.then((result)=>{
console.log(result);
}).catch((err)=>{console.log("Error ",err);})
The error
{
"message": "Missing Authentication Token"
}
I have tested the API using postman and it is working as expexted.
Probably useful to compare the request sent from your json code to the one you're sending from postman. It looks like you need to include you auth token in your headers in your request.
Something like
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authentication": `Bearer ${token}`
},
...

React Native - Sending token to Django server

So I have this react native code that sends a token in string format, yes I've checked that var token = getAccessToken() is a string and I've console.log it to ensure it is a JWT token as well. But on the Django side when I check request.headers.get('Authorization', None) it outputs: 'Bearer [object Object]' what's going on?
React Native Code
import {Auth} from 'aws-amplify';
export async function getAccessToken() {
try {
const currentUser = await Auth.currentAuthenticatedUser();
console.log(currentUser);
Auth
.currentSession()
.then(res => {
let accessToken = res.getAccessToken();
// let jwt = accessToken.getJwtToken();
// You can print them to see the full objects
// console.log(`myAccessToken: ${JSON.stringify(accessToken)}`);
// console.log(`myJwt: ${JSON.stringify(jwt)}`);
console.log(accessToken.jwtToken)
return accessToken.jwtToken
});
} catch (error) {
console.log('error signing up:', error);
}
}
const getPosts = () => {
var token = getAccessToken();
const config = {
headers: { Authorization: `Bearer ` + token }
};
axios
.get(`${url}/posts`, config)
.then(response => {
console.log(response)
setData(response.data);
})
.catch(error => {
console.log(JSON.stringify(error));
});
}
I also tried
const config = {
headers: { Authorization: `Bearer ${token}` }
};
I also tried
function getPosts() {
var token = getAccessToken().then(token => {
const config = {
headers: {
Authorization: `Bearer ${token}`
}
};
console.log(token)
axios
.get(`${url}/posts`, config)
.then(response => {
console.log(response)
setData(response.data);
})
.catch(error => {
console.log(JSON.stringify(error));
});
}).catch(error => {
console.log(JSON.stringify(error));
});;
};
and console.log(token) is outputting "undefined"
Update getAccessToken to return result of
Auth .currentSession()
And
Make getPosts function async and await getAccessToken().
OR
Use the then block to result of promise
getAccessToken().then(token=>{ // Call the api },err=>{ // Handle the error }
Otherwise what you are getting is a promise that's not resolved yet.

implementation of post web service in ionic 2 using angular2

I'm trying to implement post webservice in angular2.
I have tried to hit the URL through postman and its working. But when i'm trying to implement it in angular, I'm not getting any response.
The following is my code sample:
load(username, password) {
console.log(username," ", password);
let postData = {"username":username, "password" : password,
"userdeviceInfo": [{
"deviceId": "APA91bGUZuKVbqur7Qq2gy2eyomWgXkIU5Jcmmtmgl4IGuzVzwiJVMZgAHj3Bx6yrnW0oEZlEtB9XdcR6AOpKyEMVSWwQ_UIfNX6T0iwq28hnufOhauVdTYZQSWWPAdDrdg58cjnL5T-",
"platform":"Android"
}]};
//let body= JSON.stringify(postData);
//console.log("body---"+body)
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.url,
headers: this.headers,
body: JSON.stringify(postData)
})
console.log("body---"+this.requestoptions)
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
console.log(res.json());
return [{ status: res.status, json: res.json() }];
}})
.subscribe(res => this.data = res);
the error i'm recieving is:
XMLHttpRequest cannot load "MY_URL". Response for preflight has invalid HTTP status code 500
I'm kind of stuck here. Can anyone help me find where am i going wrong?
here is a POST example:
rate(url: string, body: { value: number}) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body, options).toPromise().then(
response => response.json(),
err => err
);
}
Of course you can delete toPromise() to use observables, this is for an example app :)
hope this can help you.
You can use this way to make a http post :
let headers = new Headers();
let body = {"username":username, "password" : password,
"userdeviceInfo": [{
"deviceId": "APA91bGUZuKVbqur7Qq2gy2eyomWgXkIU5Jcmmtmgl4IGuzVzwiJVMZgAHj3Bx6yrnW0oEZlEtB9XdcR6AOpKyEMVSWwQ_UIfNX6T0iwq28hnufOhauVdTYZQSWWPAdDrdg58cjnL5T-",
"platform":"Android"
}]};
headers.append('content-type', 'application/json');
return this.http.post("theurl", '', {
body : JSON.stringify(body),
headers : headers
})
.map(res => res.json())
.subscribe(data=>{
},
err=>{
},
()=>{
})

Trying to get then send a cookie using react and fetch

I've been trying to implement some authentication component in my app for a few hours now, and I still don't understand some of the things that are happening.
Basically, I'd like to send a POST request containing some credentials to my API, which sends me a cookie back with a token if the credentials worked. Then, the cookie should be included in the headers of all future requests to my API (which I believed was automatic).
server.js (my API is a mockup for now, with JSON files)
...
app.post('/api/login', jsonParser, (req, res) => {
fs.readFile(ACCOUNTS_FILE, (err, data) => {
if (err) {
console.error(err);
process.exit(1);
}
const accounts = JSON.parse(data);
const credentials = {
email: req.body.email,
password: req.body.password,
};
var token = null;
for (var i = 0; i < accounts.length; ++i) {
const account = accounts[i];
if (account.email === credentials.email
&& account.password === credentials.password) {
token = account.token;
break;
}
}
if (token) {
res.setHeader('Set-Cookie', `access_token=${token}; Secure; HttpOnly;`);
res.json({ token });
} else {
res.json({ token: null });
}
});
});
...
app.js
...
handleConnection(e) {
e.preventDefault();
const email = this.state.email.trim();
const password = this.state.password.trim();
if (!email && !password) {
return (false);
}
fetch(loginUrl, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
credentials: 'include',
},
body: JSON.stringify(this.state),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.warn(error);
});
return (true);
}
...
Now the console.log(data) always displays my token (or null if my credentials are wrong), but the cookie thing doesn't work...
See, I receive the Set-Cookie header, but I still have no cookie on my page.
And even if I managed to get the cookie, when I try to create a cookie using document.cookie = "access_token=123"; and then send the request again, my cookie doesn't go in my header like it would with a jQuery Ajaxcall :
I read here that adding credentials: 'include' would save the day, but unfortunately it didn't.
What am I missing here?
Thanks in advance!
I had the same problem and I found the answer in Peter Bengtsson's comment here: https://davidwalsh.name/fetch
If I understood, in your case the fetch should be:
fetch(loginUrl, {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state),
})

How to upload video to facebook via FB api with javascript?

How can I upload video files to facebook using FB api? I looked around stackoverflow but I can only find answers when the video/picture is already online somewhere, but I want to let the user directly upload a file to facebook via my application.
One solution that can upload to facebook is https://stackoverflow.com/a/8195849/364938, but it assumes I have the picture online somewhere.
Is this even possible? If if is, then how?
This is my code for uploading video using javascript from client side.I used axios for http requests, but you can use your own.
function uploadVideo(adaccount, access_token, file) {
return axios({
method: 'POST',
url: `${adaccount}/advideos`,
params: {
access_token,
upload_phase: 'start',
file_size: file.size
}
})
.then(res => {
return new Promise(resolve => {
resolve(transferVideo(
adaccount,
access_token,
res.data.upload_session_id,
res.data.start_offset,
res.data.end_offset,
file,
1
))
})
})
.catch(err => {
// Note: you can handle your error here
console.log(err)
})
}
function transferVideo(adaccount, token, sessionId, start, end, file, number) {
if (start === end) {
return new Promise(resolve => {
resolve(postVideo(adaccount, token, sessionId, file.name))
})
}
const blob = new Blob([file], {
type: file.type
})
const chunk = blob.slice(start, end, file.type)
const formData = new FormData()
formData.append(
'video_file_chunk',
chunk,
`#chunk${number}.${file.type.split('/')[1]}`
)
return new Promise(resolve => {
resolve(uploadVideoChunk(
adaccount,
token,
start,
sessionId,
formData
))
})
.then(res => {
return new Promise(resolve => {
resolve(transferVideo(
adaccount,
token,
sessionId,
res.start_offset,
res.end_offset,
file,
number++
))
})
})
.catch(err => {
throw new Error(JSON.stringify(err))
})
}
function uploadVideoChunk(adaccount, access_token, start_offset, upload_session_id, formData) {
return axios.post(`${adaccount}/advideos`, formData, {
headers: {
'content-type': 'multipart/form-data'
},
params: {
access_token,
upload_phase: 'transfer',
start_offset,
upload_session_id
}
})
.then(res => res.data)
.catch(err => {
throw new Error(JSON.stringify(err))
})
}
function postVideo(adaccount, access_token, upload_session_id, title) {
return axios({
method: 'POST',
url: `${adaccount}/advideos`,
params: {
access_token,
upload_phase: 'finish',
upload_session_id,
title
}
})
.then(res => res.data)
.catch(err => {
throw new Error(JSON.stringify(err))
})
}