Hey I'm using Directus with Ionic 3 for browser and I got a problem with HTTP PUT.
The error:
error: {code: 6, message: "Method Not Allowed"}
proto: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null,
lazyInit: ƒ}
message: "Http failure response for
http://example.com/backend/api/public/_/users?single=1&access_token=myToken&filter[id]=50:
405 Method Not Allowed"
name: "HttpErrorResponse"
ok: false
status: 405
statusText: "Method Not Allowed"
url:
"http://example.com/backend/api/public/_/users?single=1&access_token=myToken&filter[id]=50"
This my code:
updatePwd(user:any, userId: any){
return this.api.put('users?single=1&access_token=myToken&filter[id]='+userId,user).map((res: any) => {
return res;
});
}
The POST and GET work good like that
newUser(user:any){
return this.api.post('users?access_token=myToken',user).map((res: any) => {
return res;
});
}
getUser(email:any){
return this.api.get('users?single=1&access_token=myToken&filter[email]='+email).map((res: any) => {
return res;
});
}
I'm new user of Directus and I don't know much about it. So what the problem here? I must config something or what?
Thanks in advance :)
Edit:
I tried with PATCH and It works fine ^^
updatePwd(userId: any, user:any){
return this.api.patch('users/'+userId+'?&access_token=myToken',user).map((res: any) => {
return res;
});
}
Directus uses PATCH instead of PUT for updating rows: https://docs.directus.io/api/reference.html#update-user
Related
I'm using a combination of Axios and react-query to make a POST request to a server that may answer with response code 400 and validation errors.
export const axiosDefault = axios.create({
baseURL: API_LINK,
headers: {
'Content-Type': 'application/json'
},
})
const contactMutation = useMutation(
(data) => axiosDefault.post('/contact', data),
{
onSuccess: (response) => {
console.log('Success', response)
},
onError: (error) => {
console.log('Error', error)
}
}
)
However, when calling contactMutation.mutate(someData) the error response from the server does not get processed by the react query library and instead propagates upward. Neither the onSuccess or onError handlers get called, the isError property of the mutation is also not set.
I've spent hours tearing my hair out over this, what am I doing wrong?
hi i also had same issue i solved by wrapping api function to try/catch block and throw the catched Error.
(data) => {
try {
axiosDefault.post('/contact', data),
} catch (error) {
throw error
}
}
I have an app built with Nuxt.js. To get data from the API I use axios, namely #nuxtjs/axios. All request work fine but for the DELETE method.
My syntax is the following:
async removeItemFromCart(productId) {
const accessKey = await this.$store.dispatch('fetchUserAccessKey');
try {
this.$axios.delete(`/api/baskets/products?userAccessKey=${ accessKey }`, {
data: {
productId: productId
}
})
} catch (error) {
console.log(error);
}
},
However, in the console I always get the following error: createError.js?2d83:16 Uncaught (in promise) Error: Request failed with status code 400
I tried to use params instead of data, but to no avail. What am I missing here?
It seems that there's an issue with axios: when you use delete method with body, it either doesn't include payload, or deletes Content-type: 'application/json' from headers. To solve the issue, I used .request instead of .delete (according to https://github.com/nuxt-community/axios-module/issues/419)
this.$axios.request(`/api/baskets/products?userAccessKey=${ accessKey }`, {
data: {
productId: productId
},
method: 'delete'
}).
I copied the following code from Amazon Cognito Vuex Module examples to my Vue.js app:
axios.interceptors.request.use(async config => {
const response = await store.dispatch('getUserSession');
if (response && response.accessToken && response.accessToken.jwtToken) {
config.headers.awsToken = response.accessToken.jwtToken;
}
return config;
});
and expected to see in the request headers something like
awsToken: AzWDF....
, but actually I am getting:
Why 'awstoken' goes to 'Access-Control-Request-Headers' and why it does not have a value?
I also tried
config.headers.common['awsToken'] = response.accessToken.jwtToken;
but with the same result.
It is not a problem of AWS, because response.accessToken.jwtToken has a valid non-empty value.
EDIT1: and even this example does not work in my app and gives the same result:
axios.interceptors.request.use(config => {
config.headers['Authorization'] = 'Bearer XYZ';
return Promise.resolve(config);
},
(error) => {
return Promise.reject(error);
});
EDIT2: I found similar post.
I am busy with a small web app where I am trying to post to a API using a RestService but keep getting a 400 bad request. When I do the exact same post using the Insomnia Rest client I get a 200 Ok... Any idea what i'm doing wrong/what I can look at to find out what's going on?
Update:
It turns out the issue is a incorrect header, there's still a unresolved error i'm getting when trying to add the correct header...
Question continuation link Here
My error:
http://10.60.160.34/BRMServices/WebEnquiry/StockTake/AddToStockTake Failed to load resource: the server responded with a status of 400 (Bad Request)
stockTake:1 XMLHttpRequest cannot load http://10.60.160.34/BRMServices/WebEnquiry/StockTake/AddToStockTake. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 400.
main.bundle.js:47711 failure: server error
My code:
stock-take.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { RestService } from '../../services/rest.service';
import { StockTakeModel } from '../../models/stock-take.model';
#Component({
selector: 'stock-take',
templateUrl: './stock-take.component.html',
styleUrls: ['./stock-take.component.css']
})
export class StockTakeComponent implements OnInit {
stockTakeForm: FormGroup;
stockTakeModel: StockTakeModel;
constructor(private fb: FormBuilder, private restService: RestService) {
this.stockTakeForm = fb.group({
'SheetNo':['', Validators.required],
'BinNo':['', Validators.required],
'BarCode':['', Validators.required],
'Quantity':['', Validators.required]
});
}
doStockTake(val: any) {
//console.log("val:" + JSON.stringify(val));
//this.stockTakeModel = new StockTakeModel(0, 0, val[Object.keys(val)[2] '', val[Object.keys(val)[0]], val[Object.keys(val)[1]], val[Object.keys(val)[3]], 0);
this.stockTakeModel = val;
this.stockTakeModel.StockTakeID = '0';
this.stockTakeModel.IDKey = '0';
this.stockTakeModel.ProductCode = '';
this.stockTakeModel.PackSize = '0';
console.log(this.stockTakeModel);
console.log(JSON.stringify(this.stockTakeModel));
this.submitStockTake(this.stockTakeModel);
}
submitStockTake(stockTakeModel: StockTakeModel) {
//console.log(stockTakeModel);
this.restService.postStockTake(stockTakeModel)
.subscribe(
(res) => {
console.log(res);
},
(res) => {
console.log("failure: " + res);
}
);
this.stockTakeForm.reset();
}
ngOnInit() {
}
}
submitStockTake function from rest.service.ts:
postStockTake(stockTakeModel: StockTakeModel) : Observable<Response> {
console.log(JSON.stringify(stockTakeModel));
return this.http.post(this.API_URL + "StockTake/AddToStockTake", JSON.stringify(stockTakeModel), this.headers)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'server error'));
}
That indicates that you are not quite posting the same thing both ways - perhaps different request headers? Perhpas the browser running RestClient has authenticated? Inspect the actual requests in the network tab and check URL, headers, authentication etc - something has to be different.
Looking into things... here: angular.io http
it seems you aren't supposed to stringify (anymore), so try:
postStockTake(stockTakeModel: string) : Observable<Response> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.API_URL + "StockTake/AddToStockTake", { stockTakeModel }, options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'server error'));
}
You should authorise the header "Authorization" on your server side
I have also faced this issue and resolved it by removing proxy. Please check if you have set any proxy.
I am trying to upload a file to Google Cloud Storage using Json API. I am posting the request to below url with the file attachment.
https://www.googleapis.com/upload/storage/v1/b/mybucket/o?uploadType=media&name=solarsystemlrg.png
But I am getting Requested page not found. [404] Error. When I use the below Url, I am able to list the images stored in the bucket (Just to be sure that there are no access issues and bucket name is correct).
https://www.googleapis.com/storage/v1/b/mybucket/o
I have set the headers.
'Authorization' :'Bearer ' + accessToken,
'Content-Type' : contentType,
'Content-Length' : inputFile.size
Please find the code snippet below.
$.ajax({
url: targetUrl,
headers: reqHeaders,
type: 'POST',
data: reqFormWithDataFile,
async: false,
cache: false,
dataType: 'jsonp',
useDefaultXhrHeader: false,
processData: false,
success: function (response) {
alert('File Upload Successful');
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
});
Do I need to use a different URL? Or is there any other setting required? Please help.
That's the right URL, so long as you replace mybucket with your actual bucket name. After reading through jquery.ajax(), I emulated what I think is the behavior by adding &callback=foo, due to dataType: 'jsonp' and &_=1474410231688 because cache: false, and issued the request via curl and that produced a valid object with a valid callback. Can you log the entire jqXHR to see more of the status?