axios not sending file while upload - javascript

I ran into very strange issue,where my code is not sending file.
At the same time, there is no errors / warnings & console logs gives nothing.
I get HTTP 201 status, but my API catches nothing & DB entry gets created, but all with NULL field.
Almost 3 developers, scratched heads, but no one found any issue.
Here is the code for upload :
function startAll() {
$('#addTopicMediaForm').on('submit', function (event) {
event.preventDefault();
const dataArray = JSON.parse(JSON.stringify($(this).serializeArray()));
const file = $('#topic_media')[0]?.files[0];
console.log(file);
// const file = document.querySelector('#topic_media');
const fileName = file?.name;
console.log(fileName);
if (dataArray.filter((i) => i.value).length < 4 || !file) {
swal('Error', 'Please fill all required field', 'error');
return;
}
const formData = new FormData();
dataArray.forEach(({ name, value }) => {
formData.append(name, value);
});
formData.append('status', true);
if (file) {
formData.append('topic_media', file, fileName);
}
axios
.post(`${baseUrl}/topic-media/`, formData)
.then((response) => {
console.log(response);
console.log(file);
console.log(fileName);
swal('Success', 'Topic-Media added successfully', 'success');
})
.catch((err) => {
const errorData = err?.response?.data;
if (Object.keys(errorData).length > 0) {
const allErrors = serializeErrorArray(err?.response?.data);
swal(allErrors[0].name, allErrors[0].errors[0], 'error');
} else {
swal('Error', 'Something went wrong! Try again!', 'error');
}
});
});
}
});
Full HTML CODE is here :
$(document).ready(function () {
function fetchGrades() {
axios
.get(`${baseUrl}/grade/`)
.then((res) => {
const allGrades = res.data
.map((item) => {
return `<option value="${item.id}">${item.grade_name}</option>`;
})
.join(' ');
$('#grade_name').html(allGrades);
fetchSubject();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
function fetchSubject() {
axios
.get(`${baseUrl}/subject/`)
.then((res) => {
const allSubject = res.data
.map((item) => {
return `<option value="${item.id}">${item.subject_name}</option>`;
})
.join(' ');
$('#subject_name').html(allSubject);
fetchChapter();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
function fetchChapter() {
axios
.get(`${baseUrl}/chapter/`)
.then((res) => {
const allChapters = res.data
.map((item) => {
return `<option value="${item.id}">${item.chapter_name}</option>`;
})
.join(' ');
$('#chapter_name').html(allChapters);
fetchTopics();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
function fetchTopics() {
axios
.get(`${baseUrl}/topic/`)
.then((res) => {
const allTopics = res.data
.map((item) => {
return `<option value="${item.id}">${item.topic_name}</option>`;
})
.join(' ');
$('#topic_name').html(allTopics);
fetchSubTopics();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
function fetchSubTopics() {
axios
.get(`${baseUrl}/subtopic/`)
.then((res) => {
const allSubTopics = res.data
.map((item) => {
return `<option value="${item.id}">${item.subtopic_name}</option>`;
})
.join(' ');
$('#subtopic_name').html(allSubTopics);
startAll();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
fetchGrades();
function startAll() {
$('#addTopicMediaForm').on('submit', function (event) {
event.preventDefault();
const dataArray = JSON.parse(JSON.stringify($(this).serializeArray()));
const file = $('#topic_media')[0]?.files[0];
console.log(file);
// const file = document.querySelector('#topic_media');
// console.log(file);
const fileName = file?.name;
console.log(fileName);
if (dataArray.filter((i) => i.value).length < 4 || !file) {
swal('Error', 'Please fill all required field', 'error');
return;
}
const formData = new FormData();
dataArray.forEach(({ name, value }) => {
formData.append(name, value);
});
formData.append('status', true);
if (file) {
formData.append('topic_media', file, fileName);
}
//axios
// .post(`${baseUrl}/topic-media/`, formData)
axios.post(`${baseUrl}/topic-media/`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
console.log(response);
swal('Success', 'Topic-Media added successfully', 'success');
})
.catch((err) => {
const errorData = err?.response?.data;
if (Object.keys(errorData).length > 0) {
const allErrors = serializeErrorArray(err?.response?.data);
swal(allErrors[0].name, allErrors[0].errors[0], 'error');
} else {
swal('Error', 'Something went wrong! Try again!', 'error');
}
});
});
}
});
Full JS code is here :
$(document).ready(function () {
function fetchGrades() {
axios
.get(`${baseUrl}/grade/`)
.then((res) => {
const allGrades = res.data
.map((item) => {
return `<option value="${item.id}">${item.grade_name}</option>`;
})
.join(' ');
$('#grade_name').html(allGrades);
fetchSubject();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
function fetchSubject() {
axios
.get(`${baseUrl}/subject/`)
.then((res) => {
const allSubject = res.data
.map((item) => {
return `<option value="${item.id}">${item.subject_name}</option>`;
})
.join(' ');
$('#subject_name').html(allSubject);
fetchChapter();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
function fetchChapter() {
axios
.get(`${baseUrl}/chapter/`)
.then((res) => {
const allChapters = res.data
.map((item) => {
return `<option value="${item.id}">${item.chapter_name}</option>`;
})
.join(' ');
$('#chapter_name').html(allChapters);
fetchTopics();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
function fetchTopics() {
axios
.get(`${baseUrl}/topic/`)
.then((res) => {
const allTopics = res.data
.map((item) => {
return `<option value="${item.id}">${item.topic_name}</option>`;
})
.join(' ');
$('#topic_name').html(allTopics);
fetchSubTopics();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
function fetchSubTopics() {
axios
.get(`${baseUrl}/subtopic/`)
.then((res) => {
const allSubTopics = res.data
.map((item) => {
return `<option value="${item.id}">${item.subtopic_name}</option>`;
})
.join(' ');
$('#subtopic_name').html(allSubTopics);
startAll();
})
.catch(() => {
swal('Error', 'Error occurred during fetching data', 'error');
});
}
fetchGrades();
function startAll() {
$('#addTopicMediaForm').on('submit', function (event) {
event.preventDefault();
const dataArray = JSON.parse(JSON.stringify($(this).serializeArray()));
const file = $('#topic_media')[0]?.files[0];
console.log(file);
// const file = document.querySelector('#topic_media');
// console.log(file);
const fileName = file?.name;
console.log(fileName);
if (dataArray.filter((i) => i.value).length < 4 || !file) {
swal('Error', 'Please fill all required field', 'error');
return;
}
const formData = new FormData();
dataArray.forEach(({ name, value }) => {
formData.append(name, value);
});
formData.append('status', true);
if (file) {
formData.append('topic_media', file, fileName);
}
//axios
// .post(`${baseUrl}/topic-media/`, formData)
axios.post(`${baseUrl}/topic-media/`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
console.log(response);
swal('Success', 'Topic-Media added successfully', 'success');
})
.catch((err) => {
const errorData = err?.response?.data;
if (Object.keys(errorData).length > 0) {
const allErrors = serializeErrorArray(err?.response?.data);
swal(allErrors[0].name, allErrors[0].errors[0], 'error');
} else {
swal('Error', 'Something went wrong! Try again!', 'error');
}
});
});
}
});

Related

WARN Possible Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json')

WARN Possible Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json') How can I fix this problem in my code? I tried logging user and loggeduserobj both logs correctly but still, this error is coming I also logged the type of loggeduserobj it logs object Can you help me to fix this problem?
const { user } = route.params;
const [issameuser, setIssameuser] = useState(false)
const [follow, SetFollow] = useState(false)
const isMyProfile = async (otherprofile) => {
AsyncStorage.getItem('user').then((loggeduser) => {
const loggeduserobj = JSON.parse(loggeduser)
if (loggeduserobj.user.username == otherprofile[0].username) {
setIssameuser(true)
}
else {
setIssameuser(false)
}
})
}
const CheckFollow = async (otherprofile) => {
AsyncStorage.getItem('user')
.then(loggeduser => {
const loggeduserobj = JSON.parse(loggeduser);
fetch('http://10.0.2.2:3000/checkfollow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
followfrom : loggeduserobj.user.username, followto: otherprofile[0].username
})
})
})
.then(res => res.json())
.then(data => {
if (data.message == "User in following list") {
SetFollow(true)
}
else if (data.message == "User not in following list") {
SetFollow(false)
}
else {
alert('Please Try Again!')
}
})
}
useEffect(() => {
isMyProfile(user)
CheckFollow(user)
}, [])
Backend:
router.post('/checkfollow', (req, res) => {
const { followfrom, followto } = req.body;
console.log(followfrom, followto);
if (!followfrom || !followto) {
return res.status(422).json({ error: "Invalid Credentials" });
}
User.findOne({ username: followfrom })
.then(mainuser => {
if (!mainuser) {
return res.status(422).json({ error: "Invalid Credentials" });
}
else {
let data = mainuser.following.includes(followto);
console.log(data);
if (data == true) {
res.status(200).send({
message: "User in following list"
})
}
else {
res.status(200).send({
message: "User not in following list"
})
}
}
})
.catch(err => {
return res.status(422).json({ error: "Server Error" });
})
})
You need to return a Promise, the result of fetch, from your first .then() so that it can be chained on, like so:
const CheckFollow = async (otherprofile) => {
AsyncStorage.getItem('user')
.then(loggeduser => {
const loggeduserobj = JSON.parse(loggeduser);
return fetch('http://10.0.2.2:3000/checkfollow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
followfrom : loggeduserobj.user.username, followto: otherprofile[0].username
})
})
})
.then(res => res.json())
.then(data => {
if (data.message == "User in following list") {
SetFollow(true)
} else if (data.message == "User not in following list") {
SetFollow(false)
} else {
alert('Please Try Again!')
}
})
}
You should also consider using await in this case, especially since your function is already marked as async to make things more readable
const CheckFollow = async (otherprofile) => {
const loggeduser = await AsyncStorage.getItem('user');
const loggeduserobj = JSON.parse(loggeduser);
const res = await fetch('http://10.0.2.2:3000/checkfollow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
followfrom : loggeduserobj.user.username, followto: otherprofile[0].username
})
});
const data = await res.json();
if (data.message == "User in following list") {
SetFollow(true)
} else if (data.message == "User not in following list") {
SetFollow(false)
} else {
alert('Please Try Again!')
}
}

Get Out of a TextDecoderStream() from NodeJS

When I send an error message from my express nodejs app using res.status(400).send(err.stack);, I cannot seem to get out of the decoder stream I setup on the receiving end.
Here is my code in the browser (limited to the fetch portion):
fetch("/the/url", {
method: "POST",
body: formData,
}).then(response => {
if (response.status === 200) {
return response.blob().then((data) => {
return data;
});
} else {
return new Promise((resolve, reject) => {
let err_message = "";
let reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
reader.read().then(({done, value}) => {
// When no more data needs to be consumed, close the stream
if (done) {
reject(err_message);
return;
}
// Enqueue the next data chunk into our target stream
err_message += value;
});
}).then((res) => {
return (res)
}).catch((err) => {
return (err)
});
}
}).then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
});
I have put breakpoints on all subsequent then and catch but it never resolves/rejects.
Appreciate any pointers.
In case it's helpful to someone, you need to make a recursive call to the same function to break out properly.
As per the following :
fetch("/the/url", {
method: "POST",
body: formData,
}).then(response => {
if (response.status === 200) {
return response.blob().then((data) => {
return data;
});
} else {
return new Promise((resolve, reject) => {
let err_message = "";
let reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
reader.read().then(function processText({done, value}) {
// When no more data needs to be consumed, close the stream
if (done) {
reject(err_message);
return;
}
// Enqueue the next data chunk into our target stream
err_message += value;
return reader.read().then(processText);
});
}).then((res) => {
return (res)
}).catch((err) => {
return (err)
});
}
}).then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
});
from https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader

Google cloud function http trigger issue with foreach loop

I have an http trigger in cloud functions that appears to be working, however I am getting some logs that make me question the foreach loop.
Question: Is there a better way to write this function to not have to use a foreach loop?
Function:
const gamePin = req.body.gamepin
const numPlayers = req.body.playercount.toString()
var getGame = admin.firestore().collection('games')
getGame = getGame.where('gid', '==', gamePin).get()
.then(snapshot => {
if (!snapshot.empty) {
console.log(`BODY: ${JSON.stringify(req.body)}`);
snapshot.forEach(doc => {
let data = doc.data()
data.id = doc.id
console.log(`DOC DATA: ${JSON.stringify(data)}`);
const currentNumPlayers = data.playercount
console.log(`currentNumPlayers: ${JSON.stringify(currentNumPlayers)}`);
const newPlayerCount = +numPlayers + +currentNumPlayers
console.log(`newPlayerCount: ${JSON.stringify(newPlayerCount)}`);
const newPlayerCountToString = newPlayerCount.toString()
console.log(`newPlayerCountToString: ${JSON.stringify(newPlayerCountToString)}`);
var updateGame = admin.firestore().collection('games').doc(data.id)
updateGame.update({
playercount: newPlayerCountToString
}).then(res => {
console.log(`COMPLETED UPDATE: ${JSON.stringify(res)}`);
res.send({ status: 200, message: 'Game: updated.', pin: gamePin })
}).catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
res.status(500).send(err)
})
})
} else {
console.log('could not find a match ', snapshot)
res.send({ status: 400, message: 'Error. could not find a match' })
}
})
.catch(error => {
console.log(error)
res.status(500).send(error)
})
Here are the corresponding logs to go along with all those console.logs
UPDATED:
exports.addPlayerToGame = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
// Check for POST request
if (req.method !== "POST") {
res.status(400).send('Please send a POST request');
return;
}
const gamePin = req.body.gamepin
const numPlayers = req.body.playercount.toString()
var getGame = admin.firestore().collection('games')
getGame = getGame.where('gid', '==', gamePin).get()
.then(snapshot => {
if (!snapshot.empty) {
console.log(`BODY: ${JSON.stringify(req.body)}`);
const doc = snapshot.docs[0];
let data = doc.data()
data.id = doc.id
const currentNumPlayers = data.playercount
console.log(`currentNumPlayers: ${JSON.stringify(currentNumPlayers)}`);
const newPlayerCount = +numPlayers + +currentNumPlayers
console.log(`newPlayerCount: ${JSON.stringify(newPlayerCount)}`);
const newPlayerCountToString = newPlayerCount.toString()
console.log(`newPlayerCountToString: ${JSON.stringify(newPlayerCountToString)}`);
return admin.firestore().collection('games').doc(data.id)
.update({
playercount: newPlayerCountToString
})
.then((res) => {
console.log(`COMPLETED UPDATE: ${JSON.stringify(res)}`);
res.send({
status: 200,
message: 'Game: updated.',
pin: gamePin
});
})
.catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
// throw new Error(err);
res.status(500).send(err)
});
} else {
console.log('could not find a match ', snapshot)
res.send({ status: 400, message: 'Error. could not find a match' })
}
console.log(`END:`);
})
.catch(error => {
console.log(error)
res.status(500).send(error)
})
})
})
Since you want to execute in parallel several asynchronous tasks (the calls to the update() method, which returns a Promise), you need to use Promise.all(), as follows:
var getGame = admin.firestore().collection('games');
getGame = getGame
.where('gid', '==', gamePin)
.get()
.then(snapshot => {
if (!snapshot.empty) {
console.log(`BODY: ${JSON.stringify(req.body)}`);
const promises = [];
snapshot.forEach(doc => {
let data = doc.data();
data.id = doc.id;
console.log(`DOC DATA: ${JSON.stringify(data)}`);
const currentNumPlayers = data.playercount;
console.log(`currentNumPlayers: ${JSON.stringify(currentNumPlayers)}`);
const newPlayerCount = +numPlayers + +currentNumPlayers;
console.log(`newPlayerCount: ${JSON.stringify(newPlayerCount)}`);
const newPlayerCountToString = newPlayerCount.toString();
console.log(
`newPlayerCountToString: ${JSON.stringify(newPlayerCountToString)}`
);
var updateGame = admin
.firestore()
.collection('games')
.doc(data.id);
promises.push(
updateGame.update({
playercount: newPlayerCountToString
})
);
});
return Promise.all(promises)
.then(results => {
console.log(`COMPLETED UPDATE: ${JSON.stringify(res)}`);
res.send({
status: 200,
message: 'Game: updated.',
pin: gamePin
});
})
.catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
throw new Error(err);
});
} else {
console.log('could not find a match ', snapshot);
throw new Error('Error. could not find a match');
}
})
.catch(error => {
console.log(error);
res.status(500).send(error);
});
Update following your comment: If you know for sure that there is only one document returned by the Query ("there is only one document with that game pin") you can use the docs property of the QuerySnapshot which returns "an array of all the documents in the QuerySnapshot" and do as follows:
var getGame = admin.firestore().collection('games');
getGame = getGame
.where('gid', '==', gamePin)
.get()
.then(snapshot => {
if (!snapshot.empty) {
console.log(`BODY: ${JSON.stringify(req.body)}`);
const doc = snapshot.docs[0];
let data = doc.data();
data.id = doc.id;
const currentNumPlayers = data.playercount;
const newPlayerCount = +numPlayers + +currentNumPlayers;
const newPlayerCountToString = newPlayerCount.toString();
return admin.firestore().collection('games').doc(data.id)
.update({
playercount: newPlayerCountToString
})
.then(() => {
console.log(`COMPLETED UPDATE: ${JSON.stringify(res)}`);
res.send({
status: 200,
message: 'Game: updated.',
pin: gamePin
});
})
.catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
throw new Error(err);
});
} else {
console.log('could not find a match ', snapshot);
throw new Error('Error. could not find a match');
}
})
.catch(error => {
console.log(error);
res.status(500).send(error);
});
Second update, see comments in the code:
exports.addPlayerToGame = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
// Check for POST request
if (req.method !== 'POST') {
res.status(400).send('Please send a POST request');
}
const gamePin = req.body.gamepin;
const numPlayers = req.body.playercount.toString();
admin //Here I would not use a getGame variable
.firestore()
.collection('games')
.where('gid', '==', gamePin)
.get()
.then(snapshot => {
if (!snapshot.empty) {
console.log(`BODY: ${JSON.stringify(req.body)}`);
const doc = snapshot.docs[0];
let data = doc.data();
data.id = doc.id;
const currentNumPlayers = data.playercount;
console.log(
`currentNumPlayers: ${JSON.stringify(currentNumPlayers)}`
);
const newPlayerCount = +numPlayers + +currentNumPlayers;
console.log(`newPlayerCount: ${JSON.stringify(newPlayerCount)}`);
const newPlayerCountToString = newPlayerCount.toString();
console.log(
`newPlayerCountToString: ${JSON.stringify(newPlayerCountToString)}`
);
return admin
.firestore()
.collection('games')
.doc(data.id)
.update({
playercount: newPlayerCountToString
})
.then(() => { //Here, I don't understand why do you return res. The update method returns an empty Promise so just do .then(() => {}}
console.log(`COMPLETED UPDATE`); //Here don't use res, as it is the Response object and represents the HTTP response that an Express app sends when it gets an HTTP request
res.send({
status: 200,
message: 'Game: updated.',
pin: gamePin
});
})
.catch(err => {
console.log(`ERROR IN QUERY: ${JSON.stringify(err)}`);
// throw new Error(err);
res.status(500).send(err); //I am not sure what is better... throwing an Error or sending back a 500 response code.
});
} else {
console.log('could not find a match ', snapshot);
res.send({ status: 400, message: 'Error. could not find a match' });
}
console.log(`END:`);
})
.catch(error => {
console.log(error);
res.status(500).send(error);
});
});
});

TypeError: undefined is not an object (evaluating '_this.props.auth(values.username, values.password).then')

I'm developing a ReactJS app.
I'm getting the following error "TypeError: undefined is not an object (evaluating '_this.props.auth(values.username, values.password).then')".
When the "return new Promise" is outside the "then" it works properly. Nonetheless, I want to return the promise after only the two first "then"s.
Sample of loginActions.js
export const auth = (username, password) => dispatch => {
fetch('http://localhost/webservices/login', {
method: 'post',
body: JSON.stringify({ username, password })
})
.then(res => {
if(res.ok) {
console.log("Succeeded.", res);
return res.json();
} else {
console.log("Failed.", res);
return res.json();
}
})
.then(json => {
if (json.token) {
auth_status.value = true;
return auth_status.value;
} else {
auth_status.value = false;
return auth_status.value;
}
})
.then(function(res){
return new Promise((resolve, reject) => {
dispatch({
type: VERIFY_AUTH,
payload: res
});
resolve();
})
})
.catch(err => {
console.error(err);
});
};
Sample of login.js
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log("Received values of form: ", values);
this.props.auth(values.username, values.password).then(() => {
if (this.props.auth_status === true) {
message.success("Welcome!", 3);
this.setState({
redirect: true
});
} else {
message.error("The username and password combination is incorrect", 3);
}
})
.catch(err => {
console.error(err);
});
}
});
};
Your action auth is not returning anything. The return statements in the asynchronous handlers do not return for the action itself.
You need to return a Promise in your auth() action that you resolve yourself in the third then:
export const auth = (username, password) => dispatch => {
// instantly return a new promise that
// can be resolved/rejected in one of the handlers
return new Promise((resolve, reject) => {
fetch('http://localhost/webservices/login', {
method: 'post',
body: JSON.stringify({
username,
password
})
}).then(res => {
if (res.ok) return res.json();
// your probably also want to reject here
// to handle the failing of the action
reject();
}).then(json => {
if (json.token) {
auth_status.value = true;
return auth_status.value;
} else {
auth_status.value = false;
return auth_status.value;
}
}).then(res => {
dispatch({
type: VERIFY_AUTH,
payload: res
});
// resolve the original promise here
resolve();
}).catch(err => console.error(err));
});
};

Promise.all() resolves immediately

I'm trying to take some action after upload completion of multiple images, using Promise.all.
However, the code after then runs before the code being dispatched.
What am I confusing here?
submit_all_images({ dispatch, rootState }) {
const imageFileArray = rootState.imageStore.imageFileArray
var promiseArray = []
for ( var imageFile of imageFileArray ) {
promiseArray.push(dispatch('get_signed_request', imageFile))
}
Promise.all(promiseArray)
.then(results => {
console.log("finished with results: " + results)
return dispatch('submit_entire_form')
});
},
get_signed_request ({ dispatch, commit, state }, imgFile) {
const requestObject = {imageName: imgFile.name, imageType: `${imgFile.type}`}
axios.post('http://localhost:3000/sign-s3', requestObject)
.then(response => {
if (response.body.signedRequest && response.body.awsImageUrl) {
const signedRequest = response.body.signedRequest
const awsImageUrl = response.body.awsImageUrl
dispatch('upload_file', { imgFile, signedRequest, awsImageUrl })
} else {
alert('Could not get signed URL.');
}
}, error => {
console.log("ERROR: " + error)
})
},
upload_file ({ dispatch, commit, state}, { imgFile, signedRequest, awsImageUrl }) {
axios.put(signedRequest, imgFile, {
headers: {'Content-Type': imgFile.type}
}).then(response => {
console.log('finished uploading file: ' + imgFile.name )
commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)
}, error => {
alert("fail")
console.log(error)
})
},
I'm not entirely sure, since I have no experience with vuex, but I guess you're missing a few return statements.
get_signed_request({ dispatch, commit, state }, imgFile){
const requestObject = {imageName: imgFile.name, imageType: `${imgFile.type}`}
//here
return axios.post('http://localhost:3000/sign-s3', requestObject)
.then(response => {
if (response.body.signedRequest && response.body.awsImageUrl) {
const signedRequest = response.body.signedRequest
const awsImageUrl = response.body.awsImageUrl
//here
return dispatch('upload_file', { imgFile, signedRequest, awsImageUrl })
} else {
alert('Could not get signed URL.');
}
}, error => {
console.log("ERROR: " + error)
})
},
upload_file({ dispatch, commit, state}, { imgFile, signedRequest, awsImageUrl }){
//here
return axios.put(signedRequest, imgFile, {
headers: {'Content-Type': imgFile.type}
}).then(response => {
console.log('finished uploading file: ' + imgFile.name )
//and here
return commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)
}, error => {
alert("fail")
console.log(error)
})
},
So that get_signed_request returns a Promise that resolves only after axios.post().then() is done, wich depends on first resolving dispatch('upload_file', ...)
And the same for upload_file depending on resolving axios.put().then()depending on commit(types.UPDATE_LICENSE_IMG_URLS, awsImageUrl)

Categories

Resources