Vue js : Axios post getting 500 Internal Server Error - vue.js

I am using vue.js with axios to post my data.
Here i am calling two api's one on response of another with same data.
First api responds with 200 but on connecting second it returns with connection close 500 Internal Server Error.
//Axios
const formData = new FormData()
formData.append('myFile', this.chart_image);
formData.append('signal_title', this.form.signal_title)
axios.post('../api/trades/add.php' , formData, )
.then(function(response){
axios.post('../bot.php',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error.response);
});
})
.catch(function (error) {
console.log(error.response);
});
On response I am getting like this in array.
chart_image:File(777835)
lastModified:1247549551674
lastModifiedDate:Tue Jul 14 2009 11:02:31 GMT+0530 (India Standard Time) {}
name:"Penguins.jpg"
size:777835
type:"image/jpeg"
$update = json_decode(file_get_contents('php://input'));
I am using to extract the data from $update.
How to extract $update->form->chart_image->name ???
Any help would be very much helpful.
Thanks.

Related

Fetch Post of formData with images works in iOS but on android returns 400 BAD REQUEST

`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`

Axios : authorization header not set on specific request on some iOS devices

I have a vuejs app using axios for http requests.
The authorization header is set via a request interceptor like so :
const api = axios.create({
baseURL: process.env.API_URL,
crossdomain: true,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
api.interceptors.request.use(
function (config) {
if (config.url !== "/register") {
const accessToken = localStorage.getItem('token');
if (accessToken) {
config.headers.Authorization = "Bearer " + accessToken;
}
}
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
All the requests made in the app go through this interceptor. But there is a request for which the authorization header is not set for some ios devices (it works fine on web/android devices and some ios devices). Here is the request :
export function getSessions(context, payload) {
return new Promise((resolve, reject) => {
api.get("/sessions/" + payload.sportId + "/?begin=" + payload.period.from + "&end=" + payload.period.to)
.then(({ data }) => {
resolve(data);
})
.catch((error) => {
reject(error);
});
});
}
I don't understand what could be going wrong. All other requests work fine one the devices for which this one doesn't.
I found the reason of the bug : there was a / before the query (/?begin=). The problem occurred on iOS 14.5, 14.7 and maybe other versions but on any other device there was no error, sometimes a 301 http code was answered but that's it.

Get POST API Responses shown in Shopify product page/s

Need assistance, I have gotten it right to have the POST API show the responses as it should.
I need assistance with getting these responses shown on the product pages on Shopify, as they are product qty's from the supplier. I am new at this so please be easy on me...
Running the API in VisualCode with Thunder Client.
Have the following JS running but dont know if i am on the right path, it is then linked to an html to actually show the results.
fetch("URL")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then(data => {
console.log(data);
display(data)
})
.catch((error) => {
return console.error("FETCH ERROR:", error);
});
const token = localStorage.getItem('token')
const response = await fetch(apiURL, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${ttoken}`,
}
})

Axios Get Authorization Not Working In Vue But Worked on POSTMAN (Post method on vue worked)

I'm Using vue for the clientside. And somehow the Authorization is not working with Get method in axios. I tried using POSTMAN and it's working like it should be. Is there any chance that I missed something?
getCurrentPeriode() {
return new Promise((resolve, reject) => {
axios.get(TABLE_NAME,{params: {"X-API-KEY": API_KEY, command:"getCurrent"}}, {
headers:{
'Authorization': `Basic ${token}`
}
})
.then((response) => {
resolve(response.data[0])
}) .catch(err => {
reject(err.response.data)
})
})
}
The token:
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
I get this error: Uncaught (in promise) {status: false, error: "Unauthorized"}
In postman (it's worked):
I've tried with post method in axios and it's working. Yes I've set up CORS. Yes I've allowed Get method in my server side (coz it's working in postman)
Post method is working like normal, here's the code:
postNewPeriode(date) {
return new Promise((resolve, reject) => {
const data = new FormData()
data.append("dateStart", date.dateStart)
data.append("dateEnd", date.dateEnd)
data.append("X-API-KEY",API_KEY)
axios.post(TABLE_NAME,data, {
headers:{
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${token}`
}
})
.then((response) => {
resolve(response)
}) .catch(err => {
reject(err.response.data)
})
})
},
Am I missing something in my axios get or I should use different approach? Thanks for the answer
For Axios GET, the headers should be the second argument, while for PUT and POST the body is the second and the headers the third, as you did.
Try using the headers as the second argument on GET.
This should work:
axios.get( TABLE_NAME,
{
headers:{'Authorization': `Basic ${token}`},
params: {"X-API-KEY": API_KEY, command:"getCurrent"}
}
)

Fetch returns empty JSON after POST request

I'm using Fetch API to send POST request to my Express server, but I always get empty JSON ({}) instead of the data I have sent.
var postData = function (url, data) {
return fetch(url, {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(function (response) {
return response.json();
})
.then(function (data) {
return data;
});
};
var firstField = document.querySelector('#first-field').value;
var secondField = document.querySelector('#second-field').value;
if (firstField.trim().length && secondField.trim().length) {
postData('http://localhost:3000/test', { x: firstField, y: secondField })
.then(function (data) { console.log(data) })
.catch(function (error) { console.error(error) });
}
Here is the Express route:
app.post('/test', (req, res, next) => {
const x = req.body.x;
const y = req.body.y;
res.send(JSON.stringify({
x: x,
y: y
}));
});
spend the good amount of yesterday figuring this out.
You can solve it by installing cors middleware to express.
https://www.npmjs.com/package/cors
npm install cors
and add it to your app. before the body-parsers.
app.use( cors() )
app.use( bodyparser.urlencoded({ extended: true }) )
This should fix the empty body express is returning with Fetch API. Apparently using jQuery ajax post request works out of the box. Haven't investigating further why.
Good Luck.
/S