I have a simple function to test on my application:
this.$userService.getRestaurantsList(userTemp).then(
response => {
console.log(response);
console.log('FUNCIONOU');
}
);
Because I getting errors when I make this simple post, and is giving me this:
Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
This is not CORS my server is configured fine with CORS.
When we go deep to getRestaurantsList method I have this:
getRestaurantsList(user) {
return axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, JSON.stringify(user));
}
I want to send data like RAW data with AXIOS but if I use stringify it works the post, but if I use like this
getRestaurantsList(user) {
return axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, user);
}
Only the JSON data it gives me the error you guy see above, and in my API is just returning the data for testing :
This is from LARAVEL API
public function getAllRestaurants2(Request $request)
{
return $this->sendResponse($request->all(), 'Restaurants retrieved successfully');
}
Some update what I'm working on, if I send like this is working:
return axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, null, {
params: {
search: user
}
});
Only this approach that is not working:
return axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, user);
Here is my interceptor using STRINGFY and working fine log:
{
"url": "url",
"method": "post",
"data": "{\"loja\":\"teste\"}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
Now the interceptor using the wrong approach:
{
"url": "url",
"method": "post",
"data": "{\"id\":\"\",\"name\":\"Anderson Teste\",\"email\":\"teste#email\",\"client_restaurant_id\":11,\"company_id\":1,\"cpf\":\"\",\"phone\":\"81293932921393\",\"locations\":[],\"password\":\"123mudar\"}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
Here is my configuration from CORS package :
[
'paths' => ['project/api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
What I'm doing wrong that posting like JSON data format is giving me errors?
you will need to make the getRestaurantsList function asynchronous.
try this code.
getRestaurantsList(user) async {
return await axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, user);
}
Related
I am trying to pull data from the endpoint https://graph.microsoft.com/v1.0/me/. I have done this using python but I can't seem to fetch data from Microsoft Graph using vanilla js.
When I attempt to perform a fetch request. I get a 200 response but nothing is inside the response object.
Here is the fetch code:
fetch("https://graph.microsoft.com/v1.0/me/", {
method: "GET",
"headers": {
"authorization": "Bearer ENTERTOKENHERE"}
}).then(data =>{console.log(data)});
I get a response of:
Response {type: 'cors', url: 'https://graph.microsoft.com/v1.0/me/', redirected: false, status: 200, ok: true, …}
but I am expecting more of a response like the one I get from the https://developer.microsoft.com/en-us/graph/graph-explorer website like this:
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
"businessPhones": [],
"displayName": "Edd Bighead",
"givenName": "Edd",
"jobTitle": null,
"mail": "Edd#conglomo.onmicrosoft.com",
"mobilePhone": null,
"officeLocation": null,
"preferredLanguage": "en-US",
"surname": "Bighead",
"userPrincipalName": "Edd#conglomo.com",
"id": "2fa321d9-bda3-41c1-8be8-5d4049ed8765"
}
Is there anything I am missing to get the data from msgraph using vanilla js only?
I figured it out - I needed to jsonize the data then print that data. Can't believe I missed that. lol
fetch("https://graph.microsoft.com/v1.0/me/", {
method: "GET",
"headers": {
"authorization": "Bearer ENTERTOKENHERE"}
}).then(response => response.json())
.then(data => {console.log(data)})
I am building a JS Script to capture some data from the URL, this script is installed on a third-party app, so the flow is:
the user opens an URL, the Third part runs my script, my script captures that info and sends that to my server (RAILS 6), and then the third part redirects the user.
my implementation works well in chrome, but not in firefox:
console.log('before send')
try {
const response = await axios({
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
method: 'post',
url: constants.SERVER_ADDRESS,
data: click,
})
if (response.ok) {
console.log(response.json())
} else {
console.log('bad server response');
}
} catch (err) {
console.log(err)
console.log(`server error: ${err.message}`);
}
console.log('after send')
so the error that I got in firefox is: 'Error: Request aborted' and the error object doesn't have much more info.
I presume that could be an error related to my server CORS configuration?
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'localhost:3000', 'myserver.com'
resource '/api/v1/*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
allow do
origins '*'
resource '/api/v1/public/*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
what kind of configuration am I missing? or what am I doing wrong?
EDIT 1:
Looking into the details of the error with: console.log(err.toJSON())
I saw:
{
"message": "Request aborted",
"name": "Error",
"fileName": "https://server.amazonaws.com/dev.click.js",
"lineNumber": 667,
"columnNumber": 15,
"stack": "createError#https://...\n",
"config": {
"url": "http://localhost:3000/api/v1/public/click/",
"method": "post",
"data": "{...}",
"headers": {
"Accept": "application/json",
"Content-Type": "application/json"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
},
"code": "ECONNABORTED"
}
And seeing into the AXIOS Code:
...
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
that makes me think is more probably a miss configuration in Axios that makes firefox cancel the request, that make sense?
EDIT 2:
I ran the same routine using fetch instead of Axios, and I had the same result: the request worked well on chrome, but not in Firefox (or other browsers)
const headers = {
Authorization: 'Bearer fui3h73bjflkbf-hdug37o8'
}
const body = { "name": "example.com", "account": { "id": "72672yhhuo2nu2" }, "jump_start": true, "type": "full" }
let url = 'https://api.cloudflare.com/client/v4/zones'
axios.post(
url,
body,
headers
).then(console.log).catch(console.log);
Can any help me with this? I keep getting a 400 bad request from Axios - I can pass that same token over a GET request and confirm its working fine
What do you use to check the response? Here is the body of request:
{
"success": false,
"errors": [
{
"code": 6003,
"message": "Invalid request headers",
"error_chain": [
{
"code": 6111,
"message": "Invalid format for Authorization header"
}
]
}
],
"messages": [],
"result": null
}
So the problem is that you send wrong token. Check if it is correct.
You may use this one "Bearer YQSn-xWAQiiEh9qM58wZNnyQS7FUdoqGIUAbrh7T" from cloudflare site to check if you will get 403 Forbidden instead of your current 400. If so, your request is fine, and you just need correct token.
It was formatting
var config = {
headers: {'Authorization': "Bearer fui3h73bjflkbf-hdug37o8"}
};
can you please help me how to get to work POST method in vanilla JS (without jQuery)?
I am trying to do it with this code:
var call =
{
"filterParameters": {
"id": 18855843,
"isInStockOnly": false,
"newsOnly": false,
"wearType": 0,
"orderBy": 0,
"page": 1,
"params": {
"tId": 0,
"v": []
},
"producers": [],
"sendPrices": true,
"type": "action",
"typeId": "",
"branchId": ""
}
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.alza.cz/Services/RestService.svc/v2/products');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('OK ' + xhr.responseText);
}
else if (xhr.status !== 200) {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(call);
And constantly getting error 400 (Bad request).
I have tried to call it in jQuery and it is working, but I need to get it work in plain JS.
Please, any idea why it is not working?
For check, here is the working code in jQuery:
addData({
"filterParameters": {
"id": 18855843,
"isInStockOnly": false,
"newsOnly": false,
"wearType": 0,
"orderBy": 0,
"page": 1,
"params": {
"tId": 0,
"v": []
},
"producers": [],
"sendPrices": true,
"type": "action",
"typeId": "",
"branchId": ""
}
}
);
function addData(data){// pass your data in method
$.ajax({
type: "POST",
url: "https://www.alza.cz/Services/RestService.svc/v2/products",
data: JSON.stringify(data),// now data come in this function
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
console.log(data);// write success in " "
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('fail' + status.code);
}
});
}
You must set the content-type header to application/json You are posting json data as formdata which is wrong (beside you have forgotten to stringify your object)
xhr.setRequestHeader('Content-Type', 'application/json');
Heres is a working example using the new vanilla js fetch API
var result = null
fetch("https://www.alza.cz/Services/RestService.svc/v2/products", {
method: "POST",
body: JSON.stringify({
"filterParameters": {
"id": 18855843,
"isInStockOnly": false,
"newsOnly": false,
"wearType": 0,
"orderBy": 0,
"page": 1,
"params": {
"tId": 0,
"v": []
},
"producers": [],
"sendPrices": true,
"type": "action",
"typeId": "",
"branchId": ""
}
}),
headers: {"content-type": "application/json"},
//credentials: 'include'
})
.then(function(res) {
if (res.ok) { // ok if status is 2xx
console.log('OK ' + res.statusText);
} else {
console.log('Request failed. Returned status of ' + res.status);
}
return res.blob()
})
.then(function(blob) {
result = blob
// window.result = blob
})
It's the Access-Control-Allow-Origin response blocking the Javascript code to AJAX access the server data. If the server is not controlled by you, you need another server to fetch the data instead, before it can redirect to your webpage.
So I just tried xhr.send()
and got
XMLHttpRequest cannot load https://www.alza.cz/Services/RestService.svc/v2/products. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://www.alza.cz' that is not equal to the supplied origin.
However if I try this on a blank tab, it actually works.
what url are you trying to run this JS from?
Try running the JS from a blank tab.
in a $http error handler, I need to differentiate a real HTTP error from cancelled requests.
Here is an example:
app.controller('Ctrl', function ($http, $q) {
const vm = this;
this.errors = [];
vm.errorHandler = (label) => ((error) => {
this.errors.push(label + ' : \n\n' + JSON.stringify(error, null, 2));
});
vm.unResolved = () => {
$http({
method: 'GET',
url : 'https://Idonotexist'
}).catch(vm.errorHandler('unResolved'));
}
vm.cancelled = () => {
const canceller = $q.defer()
$http({
method: 'GET',
timeout: canceller.promise,
url : 'https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699'
}).catch(vm.errorHandler('cancelled'));
canceller.resolve();
}
vm.unsecured = () => {
$http({
method: 'GET',
url : 'http://Idonotexist'
}).catch(vm.errorHandler('unsecured'))
}
});
In my errorHandler function, I want to differentiate cancelled requests from a real error (such as "insecured" or "unresolved hosts").
It would be a real pain for me to pass the canceller to the error handler and it won't be able to treat correctly requests cancelled by the browser without an angularjs canceller.
So far, here are the errors I get in my error handler.
Error for non cancelled (host unresolved) request :
{
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"jsonpCallbackParam": "callback",
"url": "https://Idonotexist",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": ""
}
Error for cancelled request :
{
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"jsonpCallbackParam": "callback",
"timeout": {
"$$state": {
"status": 1,
"processScheduled": false,
"pur": true
}
},
"url": "https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": ""
}
I have a config.timeout that contains the promise but I would like to avoid using it. I would like to treat as cancelled requests requests cancelled by the browser even if no canceller.
Here is a jsfiddle with the example.
Is there a way to add a interceptor on cancelled requests to flag then specifically ?
UPDATE
This can't be solved angularjs $http code does not separate error than timeout or abort. You can see it here.
A pull request is running about it.