I have a problem when making an axios request, it returns a 404 error, the file path is fine since it is in the same directory and I do not understand why it returns that error,
I am using vue-cli, and I run the server with npm run serve instead of express.
Register.vue
var formData = new FormData();
formData.append("nombre", nombre);
formData.append("mail", mail);
formData.append("pass", pass);
axios
.post("./auth_register.php", formData)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
auth_register.php
<?php
if (isset($_POST['nombre']) && $_POST['mail'] && $_POST['pass']) {
return json_encode("received");
} else {
return null;
}
I don't know why this happens
I am new to vue do not be angry
Try using the full path; Worked for me! after long searching
example -> http://localhost:8080/api/authentication/login.php
Related
I have an app scenario with react native and CodeIgniter as backend.
I have a code snippet to upload image as picked by react-native-image-picker as below:
let formData = new FormData();
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
formData.append('file', (imageBody)) // case 1 gives network error
formData.append('file', JSON.stringify(imageBody)) //case 2 goes OK
apiUpdateUser(formData)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
The apiUpdateUser method goes as :
export const apiUpdateUser = body => {
return new Promise((resolve, reject) => {
axios
.post(ApiRoutes.updateUser, body, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(Constant.network.networkError);
});
});
};
The Php code at the backend to handle this upload as usual is:
$file=$this->request->getFile('file');//in CI
$file=$_FILES['file'];//in normal php
My issue is that I do not get anything whatsoever in the $file variabe with either of the methods, The file variable is empty in both the cases.
I've checked the implementation in react native and it doesnt seem to be buggy at all comparing with tutorials/demonstrations online. Also the way of handling at the backend is obvious and Ok.
I'm able to achieve this upload with POSTMAN easily but with react-native I'm facing this error. Can anyone show me some light here??
I am using VUE and sending files using Axios. So I think this may help you out.
I am using the following way of form data to set the files or images.
formData.append('file', this.form.image_url, this.form.image_url.name);
Here this.form.image_url directly refers to the $event.target.files[0]; where $event targets the input.
In the backend, it is the same as you have it here.
This works out well for me. I am unsure of what you are passing as imageBody so it's hard to comment on that.
You can try this
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
apiUpdateUser(imageBody)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
export const apiUpdateUser = body => {
return new Promise((resolve, reject) => {
axios
.post(ApiRoutes.updateUser, body, {
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(Constant.network.networkError);
});
});
};
Turns out that the JSON.stringify() was the culprit line.
Without that line, the app was giving out network error.
That's why I had randomly added it just to see if that was the cause of error.
Since, the network error issue was solved with that addition, I didn't give a second thought about it and only thought it to be a file upload issue. Actually, I now see that this is a known issue of a react native flipper version that I have been using which I managed to solve.
I have PHP page on a web server to upload image from React Native.
Using Postman method POST, form-data key:avatar value: image_file everything works as expected.
In React Native I tried:
let uploadData = new FormData();
uploadData.append('avatar', uploadUri);
fetch(base_url, { method: 'post,', body: uploadData }).then(
(res) => {
var myresponse = res;
console.log(JSON.stringify(myresponse));
//console.log(res);
}
);
I am getting from server error:
{"type":"default","status":400,"ok":false,"headers":{"map":{"server":"Apache","connection":"Upgrade,
close","content-type":"text/html","vary":"Accept-Encoding,User-Agent","date":"Wed,
20 May 2020 15:29:15
GMT","accept-ranges":"bytes","upgrade":"h2,h2c"}},"url":"http://www./uploadImage.php","_bodyInit":{"_data":{"size":10154,"offset":0,"blobId":"D8041FEE-0479-4CD5-8438-4EFD737561DE","type":"text/html","name":"uploadImage.php","__collector":{}}},"_bodyBlob":{"_data":{"size":10154,"offset":0,"blobId":"D8041FEE-0479-4CD5-8438-4EFD737561DE","type":"text/html","name":"uploadImage.php","__collector":{}}}}
Than I tried using axios:
let uploadData = new FormData();
uploadData.append('avatar', uploadUri);
axios.post(base_url, uploadData).then((res) => {
console.log(res);
});
I get this response from the server:
"error": true,
"message": "No file was sent!",
"status": "error",
It is failing on: if($_FILES['avatar']), in PHP.
I have no idea what to do any more, again in Postman everything works fine as expected.
Does anybody have any idea what to do?
I tested it again and it is to be a problem with the URI that I am sending, for sure.
ie. if I look in Postman the request that I am sending:
avatar=#/Users/......image.jpg
and in React Native I am sending:
"avatar","file:///Users/.....image.jpg
By the way, I am using expo-image-picker to select the image.
It looks like this did the work..
let body = new FormData();
//Appending file to body
body.append('avatar', {
uri: uploadUri,
type: 'image/jpeg', //This is the file type .. you can define according to your requirement
name: 'avatar.jpg', //File name you want to pass
});
//Service call
fetch(base_url, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
body: body,
})
.then((res) => res.json())
.then((responseJson) => {
//GET RESPONSE SUCCESS OF FAILURE
console.log(JSON.stringify(responseJson));
})
.catch((error) => {
//ERROR
console.log(JSON.stringify(error));
});
I am posting data to Laravel and expect a success response, but it catches the exception TypeError: Network request failed. Using get methods and login post methods using Laravel passport works all fine.
Adding 'Content-Type': 'application/json' to headers creates Network request failed for the login methods.
Postman returns valid errors or success, so works totally as expected.
Debugging showed that the request has been sent to Laravel and routing is correct as Visual Studio Code debugger stops at a breakpoint at return response.
public function postMessages()
{
...
return response()->json(['success' => 'success'], 200);
}
Route::middleware('auth:api')->group(function () {
Route::post('messages', 'Api\ChatController#postMessages');
});
export const fetchApi = async (endPoint, method = 'get', body = {}) => {
const accessToken = authSelectors.get().tokens.access.value;
const accessType = authSelectors.get().tokens.access.type;
let headers = {
...(accessToken &&
{
Authorization: `${accessType} ${accessToken}`
}
)
};
let response;
if (method=='get' || Object.keys(body)==0 ) {
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers
});
} else {
var formData = new FormData();
Object.keys(body).forEach(type => {
formData.append(type, body[type]);
});
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers,
body: formData
});
console.log('fetch response: ' + JSON.stringify(response));
}
let responseJsonData = await response.json();
return responseJsonData;
}
export const postMessages = (eidug, type, name, messages) => fetchApi('/message', 'post', {
'eidug': eidug,
'type': type,
'name': name,
'messages': messages
});
I expect a response without any exception like Postman. What can be going wrong?
Have you enabled CORS in the backend? Once open inspect->network and then run fetch. Show if there are any errors.
I spent time before asking this question
I want to download file from local directory /Users/Desktop/symfony/project_dem/app/Resources/file.webm, but i always get something wrong.
So my controller
public function getUrl(Request $request)
{
$response = new BinaryFileResponse($file);
$response->setAutoEtag(true);
$response->headers->set('Content-Type', 'video/webm');
return $response;
}
in VueJS
axios.post('/api', {
url: this.url,
responseType: 'blob',
}).then((response) => {
console.log(response.data);
let blob = new Blob([response.data], {
type: 'video/webm'
}),
url = window.URL.createObjectURL(blob);
window.open(url);
}).catch(error => {
console.log(error);
});
I get in console log for response.data like this
**
What I found wrong is why the size of the file in server 6.2 MB and after a download is 11.2 maybe this is error BinaryFileResponse ?
**
Anyone can tell me what I did wrong ? and thanks.
So it seems that the output of console.log(response.data) is showing a binary file. I mean the file is there. You are not clear when you say
but I always get something wrong
Try this
axios.post('/api', {
url: this.url,
responseType: 'blob',
}).then((response) => {
let blob = new Blob([response.data], {
type: 'video/webm'
});
url = window.URL.createObjectURL(blob);
window.open(url);
}).catch(error => {
console.log(error);
});
In my opinion, the issue here is that you did not put a semi colon at the end of the line where you created the blob.
I have a problem following this tutorial to implement a simple chat in Laravel using Pusher and Vue.js: link tutorial.
First of all my route in the navbar is this one:
http://localhost/youChat/public/
My web.php file contents the following routes:
Auth::routes();
Route::get('/', 'TweetController#index');
Route::get('tweets', 'TweetController#showTweets')->middleware('auth');
Route::post('tweets', 'TweetController#sentTweet')->middleware('auth');
My app.js file in assets/js where I make the request is this one:
const app = new Vue({
el: '#app',
data: {
tweets: []
},
created() {
this.showTweets();
Echo.private('chat')
.listen('TweetSentEvent', (e) => {
this.tweets.push({
tweet: e.tweet.tweet,
user: e.user
});
});
},
methods: {
showTweets() {
axios.get('/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('/tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
});
As you can see I send the request with Axios.
Everything seems looks fine but the GET and POST request are not working. The error in the console inspector shows this:
GET http://localhost/tweets 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (app.js:13931)
at settle (app.js:35401)
at XMLHttpRequest.handleLoad (app.js:13805)
GET https://stats.pusher.com/timeline/v2/jsonp/1session=Njg3NjQyNDY5NT....MjY1fV0%3D 0 ()
POST http://localhost/broadcasting/auth 404 (Not Found)
And when I try to make a POST:
POST http://localhost/tweets 404 (Not Found)
The get/post should go to this direction:
http://localhost/youChat/public/tweets
but I don't know what's happening. Any suggestion? I'm desperated :D.
Thanks in advance!
You are getting this error because you are using an absolute path.
So either you can store the Base url in a variable or you can use relative path
here is an example.
methods: {
showTweets() {
axios.get('tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
Remove the / before the URL or
save a
const URL = '{{url('/')}}'
methods: {
showTweets() {
axios.get(URL + '/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post(URL + '/tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
Hope this helps