I'm having an issue with loading json data locally. My code worked fine when I loaded data from https://randomuser.me/api, but when I specify location of my json file locally it just returns plain HTML. Definitely doing something wrong, but can't figure it out. I use axios for ajax calls. How do I make the request correctly? My code:
export function fetchUsers () {
return {
type: 'FETCH_USER',
payload: axios.get('./users.json').then( (response) =>
console.log(response.data) )
};
}
Related
I've been trying to upload an image with axios to an external (laravel) api and it's been giving me nightmares.
resumed template:
<v-form>
<v-file-input
label="Logo*"
v-model="image"
accept="image/*"
#change="onFileSelected"
required
></v-file-input>
<v-btn color="blue darken-1" text #click="createProvider">Create Provider</v-btn>
</v-form>
Methods
methods: {
onFileSelected (event) {
this.selectedImage = event;
},
createProvider() {
let formData = new FormData();
formData.append("image", this.selectedImage, this.selectedImage.name);
const config = {
headers: {
Authorization: this.token,
'content-type': 'multipart/form-data'
}
};
let imageData = {
'image': formData,
'name': 'Provider Image', // Required Field
}
axios.post('http://fake_external_url.com/api/images', imageData, config) // laravel API
.then(console.log)
.catch(console.log)
},
}
The error that I get in return is:
Error: Request failed with status code 422
Request Response:
[HTTP/1.1 422 Unprocessable Entity 1374ms]
{"image":{},"name":"Image Provider"}
I see that the image is not receiving anything.
If I console.log this.selectedImage I get:
File {
name: "happy.jpg",
lastModified: 1596711013544,
webkitRelativePath: "",
size: 41292,
type: "image/jpeg"
}
If I console.log FormData I get crap
FormData
<prototype>: FormDataPrototype
append: function append()
constructor: function ()
delete: function delete()
entries: function entries()
forEach: function forEach()
get: function get()
getAll: function getAll()
has: function has()
keys: function keys()
set: function set()
values: function values()
Symbol(Symbol.toStringTag): "FormData"
Symbol(Symbol.iterator): function entries()
<prototype>: Object { … }
My environment: localhost on a XAMPP server (php artisan serve as well). Laravel, VueJS, Vuetify latest versions.
I think my problem likes in my FormData, but it may be from the variables that it's receiving from the event click. I am out of ideas.
[EDIT] Note: I am able to upload image when using POSTMAN.
The reason why I am using event, and not the classic event.target.files[0] it's because there is no target in the response from the console.log.
You have two problems.
FormData
You need to send a FormData object, only a FormData object, and nothing but a FormData object.
If you want to pass additional data, then append it to the FormData object.
Wrapping the FormData object in another object and passing it to (for example) a JSON serializer will just break it.
Content-Type
The multipart/form-data MIME type has a mandatory boundary parameter.
You have omitted it, but you can't know what it is anyway.
Do not set the Content-Type header manually. The underlying XHR object will read it from the FormData object.
I am working on some charts in d3.js v5.8.2 and I want to load JSON data that I get from an API request which needs an authorization header. I tried something like:
d3.json('url')
.header("Authorization", "Bearer 7tsBVpsiYT")
.get(function(error, data) {
// callback
console.log(data);
});
I get the following error message:
Uncaught TypeError: d3.json(...).header is not a function
Since D3 v5 uses the Fetch API as a replacement for the XMLHttpRequest which was used by prior versions the API for d3.json() needed to be changed a bit. From the docs:
# d3.json(input[, init]) <>
Fetches the JSON file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch; see RequestInit for allowed fields.
You now have to pass the Authorization header via the RequestInit object which is passed as the optional second argument to d3.json(). As Mike Bostock explains in his basic demo Fetch with Basic Auth this can be done using the native Fetch API:
fetch("https://httpbin.org/basic-auth/user/passwd", {
headers: new Headers({
"Authorization": `Basic ${base64.encode(`${login}:${password}`)}`
}),
}).then(response => {
if (!response.ok) throw new Error(response.status);
return response.json();
});
Looking at the source of d3.json() one notices that above code is basically equivalent to what D3 does internally while executing d3.json. Thus, the code can be rewritten as:
d3.json("https://httpbin.org/basic-auth/user/passwd", {
headers: new Headers({
"Authorization": `Basic ${base64.encode(`${login}:${password}`)}`
}),
}).then(json => { /* do something */ });
I have a vuex which stores few informations and also the files uploaded by the users. Now I am trying to send all the vuex data to backend using axios to process it but for some reason the file array is empty.
But when I see in VueDevTools, there is a file object in the vuex state.
This is my axios call, it is just not images which I am trying to send.
axios.post('/admin/form/saveForm',{
data : this.$store.getters.getEditCollector,
formData: this.$store.getters.getCollector,
formName : this.formName,
task: this.task,
id: this.formEntryId,
formId: this.formId,
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {})
.catch(error => {});
My Vuex is below snapshot.
As we can see, the logo state has a File Object, but when the request is received in the backend( PHP- Laravel), It is an empty array.
What is wrong here? Can someone point out the mistake?
EDIT1: Added Network Payload
EDIT2: Added Backend Code - Laravel
public function saveForm(Request $request){
// form data here has logo but empty array <------
$formData = $request->input('data');
$wholeFormData = $request->input('formData');
$this->formID = $request->input('formId');
....
...
}
I have been doing React JS a while, but only front-end. Now I would like to spice it up with external data. So I tried with AXIOS / FETCH unfortunatelly both of them produced this miserable result. Here is the challenge:
fetch("http://localhost:8080/backend/datatest/src.json", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
fetch('http://localhost:8080/backend/datatest/src.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log(json)
})
Its basicly a copy-paste from GITHUB of fetch, assuring nothing would go badly. "GET" function works perfectly, but i got problems with POST-ing. I keep getting back the same error mesage
POST http://localhost:8080/backend/datatest/src.json 404 (Not Found)
HOWEVER! GET works perfectly.
I am using React JS, Redux, node JS. This JSON file didnt get installed at any server. In your opinion what would be the next step.
Regards,
Koppany
I have developed a template (feedheader.hbs) which I am rendering in my feed template like {{ render 'feedheader' feedheader}}.This feedheader contains the username and profile pic of user.I need to send the the requests to http://example.com/api/users/profile/?targetuser=-1 along with my auth header to get the user details.So I made a controller for feedheader and made the ajax requests.I am using ember-simple-auth (fb login ) for authorization.
controller.js
import Ember from 'ember';
import OAuth2Bearer from 'ember-simple-auth/authorizers/oauth2-bearer';
const { service } = Ember.inject;
export default Ember.Controller.extend(OAuth2Bearer,{
session:service('session'),
init:function(){
this.get('session').authorize('authorizer:application', (headerName, headerValue) => {
const headers = {};
headers[headerName] = headerValue;
Ember.$.ajax('http://example.com/api/users/profile/?targetuser=-1', { headers });
});
}
});
But it throws an error in console
"Uncaught Error: Assertion Failed: Expected hash or Mixin instance, got [object Function]"
authorizers(application.js)
import OAuth2Bearer from 'ember-simple-auth/authorizers/oauth2-bearer';
export default OAuth2Bearer.extend();
The authorizers is working fine in my adapter.There is some simple thing I am missing and not able to fix this.Please tell how to send the ajax request with my authorizers header.
The way you're sending the headers doesn't look right to me. Instead of
Ember.$.ajax('http://example.com/api/users/profile/?targetuser=-1', { headers });
it should be
Ember.$.ajax('http://example.com/api/users/profile/?targetuser=-1', { headers: headers });