i have code axios :
var url =`laporan_type=${typeLaporan}&provinsi_id=${id_provinsi}&id_kabkota=${id_kabkota}&id_kecamatan=${id_kecamatan}&year=${year}&month=${month}`
axios({
method: 'get',
url: `${simkah}/laporan/reportWord?${url}`,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
responseType: "blob"
}).then(
(response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
}
).catch((error) => {
console.log(error);
});
and i get error CORS. Can you help me pls ( i have seen many topic and i still don't understand why it is not working
CORS is to be set on the backend, Ask your backend laravel developer to create a CORS middleware and pass that in API routes. So whenever you send the request from API just send all the headers you'll get a successful response.
To create middleware in laravel just followed any suitable tutorials or create it on your own.
Middleware tutorial:
https://www.stackhawk.com/blog/laravel-cors/
Related
I am now trying to make a crud functionality with file upload on my project. I have done the creation part and it's all working fine since I implemented that with new FormData() by appending the file value and sending post request from axios with headers 'Content-Type': 'multipart/form-data'.
However, axios sends an empty body if I pass 'Content-Type': 'multipart/form-data' in the headers. If I remove it, it sends the actual object but without the uploaded file. I am implementing this on NextJs with Laravel backend.
Here's the code
const formData = new FormData();
formData.append('first_name', values.first_name);
formData.append('last_name', values.last_name);
formData.append('phone_no', values.phone_no);
formData.append('profile_picture', values.profile_picture, 'bermuda.png');
formData.append('password', values.password);
await axios
.put(`/api/v1/users/${user.member_no}`, formData,
{
headers: {'Content-Type': 'multipart/form-data'}
})
.then((res) => {
console.log(res.data);
if (res.status === 201) {
toast.success('Member updated successfully.');
refreshUser(); // mutating the swr request
}
})
.catch((err) => {
toast.error(err.response.data.message);
});
setLoading(false);
},
console.log(res.data); from axios returns [] if I pass multipart/form-data or it returns the whole value object if i remove it but wihout the uploaded file.```
This seems to be a common re-occurring problem within Laravel projects. Not sure if it's caused by Axios or Laravel itself, but for the meantime, the following workaround works:
Instead of sending an actual HTTP PUT request, send an HTTP POST request with a parameter in your formData named _method with its value set to put. This is a feature in Laravel known as method spoofing.
Adding that field to your formData, your code would look like this:
const formData = new FormData();
formData.append('_method', 'put');
formData.append('first_name', values.first_name);
formData.append('last_name', values.last_name);
formData.append('phone_no', values.phone_no);
formData.append('profile_picture', values.profile_picture, 'bermuda.png');
formData.append('password', values.password);
await axios
.post(`/api/v1/users/${user.member_no}`, formData,
{
headers: {'Content-Type': 'multipart/form-data'}
})
.then((res) => {
console.log(res.data);
if (res.status === 201) {
toast.success('Member updated successfully.');
refreshUser(); // mutating the swr request
}
})
.catch((err) => {
toast.error(err.response.data.message);
});
setLoading(false);
},
I'm trying to send a get request with fetch API to ask the brawl stars API server. I've created an API KEY associated with my IP address. I've tried everything, but I got a 403 response from the server.
Here is my code :
const url = 'https://api.brawlstars.com/v1/players/...';
const token = '...';
const headers = new Headers({
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
});
const options = {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
};
fetch(url, options)
.then(response => response.json())
.then(console.log)
.catch(console.error);
In the console there is the message : No 'Access-Control-Allow-Origin' header is present on the requested resource because of cors policy.
When I test the request on Insomnia, it works well !
I had a problem with the Brawlstars API a little while back when I was making a Brawlstars command for my Discord bot. I was able to get the API to work however with the following code.
const playerurl = 'https://api.brawlstars.com/v1/players/';
const getJSON = async url => {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer <yourapitoken>',
},
});
if(!response.ok) {throw new Error(response.statusText);}
const data = await response.json();
return data;
}
catch(error) {
return error;
}
};
getJSON(playerurl).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
I hope this works for you!
I have created Spring as backend and enabled social login for google authentication. /signin/google is the endpoint with a method POST and content type is application/x-www-form-urlencoded with scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email.
Postman client works perfectly fine if i invoke the above mentioned endpoint from postman client(Google chrome app) it gives me 200 status code and JSESSIONID and i am able to invoke the other secure api.
but for react native i am unable to execute it. Help would be highly appreciated. Mentioned below is the function that i am using to trigger google signin.
googleSignin = () => {
var data = 'scope=' + encodeURIComponent('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email');
axios({
url: baseUrl + 'signin/google',
method: 'POST',
data: data,
config: {
headers:
{
'cache-control': 'no-cache',
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': true
},
credentials: "same-origin"
},
withCredentials: true
})
.then(res => {
console.log('googleSignin res() ---> ', res.headers);
})
.catch(e => console.log(e));
};
It always gives me CORS error policy. mentioned below is the cors configuration on the backend.
allowed-origins: "*"
allowed-methods: "*"
allowed-headers: "Access-Control-Allow-Headers, Authorization, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"
exposed-headers: "Authorization,Link,X-Total-Count"
allow-credentials: true
max-age: 1800
and screenshot is the error:
This is a cross-domain issue. After jQuery 1.5.0 and later, the cross-domain was blocked. As a result, the following error occurs when requested by ajax:
Try this code.
const options = baseUrl + 'signin/google'
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = [removed].protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
$.post(
options,
function (response) {
console.log(">>>> " + JSON.stringify(response));
});
I am implementing a login. I can send a post request to the endpoint token in Postman but not in axios.
Axios function:
axios({
method: 'post',
url: 'http://localhost:20449/token',
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
data: {
'grant_type': 'password',
'username': user.username,
'password': user.password
}
}).then(resp => {
console.log(resp)
commit(AUTH_SUCCESS, resp)
dispatch(USER_REQUEST)
resolve(resp)
})
I get the error
"unsupported_grant_type"
I found a solution. Axios uses application/json by default when data is an object. It did not worked even after adding application/x-www-form-urlencoded in header. So I downloaded the package qs (npm install qs --save). I imported the package and use the axios command below:
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });
I'm developing an netcore MVC application which uses Ajax requests to POST data to the server. I am using IdentityServer4 as my auth middleware. The flow is when the application is launched with a URL of http://localhost:6002 it redirect to IdentityServer (localhost:6000). The user logs in and is redirected to the main application which then works fine.
Ajax GET requests also work correctly. I can observe a list of claims on the Get action in the controller (User.Identity.Claims). However when I try a POST data from the server the request returns a 200 but from the Identity Server with Redirect=true
My call from the Javascript
applyUpdate(modelData) {
let that = this;
fetch("http://localhost:6002/Client/Update/", {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(modelData)
}
).then(function (response) {
return response;
}).then(function (outData) {
alert("saved");
});
}
The response I receive is
{type: "cors",
url: "http://localhost:6000/account/login?returnUrl=%2Fc…%26x-client..,
redirected: true,
status: 200,
ok: true}
I have enabled CORS on the applications as previously I was getting 405 issues. What appears to be happening is when I call my controller action from Javascript a redirect is being performed to IdentityServer which is then returning to the client without ever actually executing my action.
My controller action looks like
[Authorize]
[HttpPost]
public async Task<JsonResult> Update([FromBody] MyVM myVM)
{
}
If I remove the [Authorize] attribute the method is reached however the value of User.Identity.Claims is always empty where in a HTTP Get it contains a list of all my claims.
Below is the relevant section for configuring IdentityServer from the Startup.cs file
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = identityUrl;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role",
};
options.ClientId = "my client";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.UseTokenLifetime = false;
});
I am absolutely stumped at this behavior, any help would be greatly appreciated
UPDATE
Bizarrely I am using the Javascript Fetch API to do the POST, when I swap it out of use Jquery Ajax it works perfectly so many it's the Fetch API that isn't managing the Redirect. This call works fine
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: 'http://localhost:6002/Client/Update/',
data: JSON.stringify(modelData),
success: function success(msg) {
alert("saved");
},
error: function error(xhr, data, err) {
console.log(xhr);
}
});
I didn't want to have to include a dependency Jquery