I can retrieve data from the validator of Laravel. My application vue.js is multilingual. I wish I could recover the errors of Laravel but translated.
I'm trying to send the axios query with the Accept-Language headers
A log console of my request :
{url: "auth/login", method: "post", data: {…}, headers: {…}, baseURL: "http://myapp.test/api", …}
adapter: ƒ xhrAdapter(config)
baseURL: "http://myath.test/api"
data: "{"email":"jeremy#myapp.test","password":"password"}"
headers:
Accept: "application/json, text/plain, */*"
Accept-Language: "en"
Content-Type: "application/json;charset=utf-8"
We see that my request sends "Accept-Language".
But my errors are always returned in Laravel's default language
This is how I do with Nuxtjs :
export default async function ({ $axios }) {
$axios.onRequest((config) => {
console.log(config)
config.headers.common['Accept-Language'] = 'en'
})
}
Do you have an idea? Can you explain to me?
Thank you !
Related
I use Axios in browser to call ajax request. Now I have a problem with some cookie that has high priority than some header. Per request I send a header as AUTHTOKEN but in cookie SESSIONID key stored that high priority than AUTHTOKEN header. In some scenario, I need to ignore cookie. This is my code:
axios({
url:`${sdpBasicUrl}/api/v3/requests/27363`,
method: 'get',
headers: {
'Content-Type': 'application/json'
'AUTHTOKEN': 'GHG23847923HGJ'
}
})
.then(res => {
console.log(res.data);
});
and this is cookie sample:
_z_identity=true; PORTALID=1; csrfcookie=aasdasdjh24234b2bjh4hjl; SESSIONID=ffd68d32a14841c99905e3cf4897e15ec9b4777020854a76821fd7e1eab6db2dcab482eb4cfea2ce7f5a6c47c80271d09f608ed985004e5c85681b2939681b18
What should I do? Do you have any solution to solve my problem?
You are able to pass in cookies through the header like this:
Axios.request({
url: "http://example.com",
method: "get",
headers:{
Cookie: "cookie1=value; cookie2=value; cookie3=value;"
}
}).then...
So if you don't want the value to be there, you could override the values.
https://github.com/axios/axios/issues/943
You can use transformRequest to modify the header for some requests. transformRequest allows changes to the request data and header before it is sent to the server. This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'.
transformRequest: [function (data, headers) {
// Modify the header here and return the header
return data;
}],
You can get more information about it on https://axios-http.com/docs/req_config
So based off Cypress request docs: https://docs.cypress.io/api/commands/request.html
It seems like I should be able to send a POST request with a JSON body pretty easily. So this is what I tried:
cy.fixture('test_create').as('create_test')
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: '#create_test',
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
However when I look at the "commands" Cypress sends, it's sending the body as literally Body: #create_test
Is it not possible to use a fixture within the body of a POST request? I confirmed the fixture is loading correctly. I confirmed also it works when I paste the entire JSON inside of the body option....but that gets ugly really quick with large JSON bodys.
You get a literal because in the form cy.request(options), options is a plain JS object and unfortunately not parsed by Cypress to interpret the alias.
The request form cy.request(method, url, body) probably does allow an alias for the body param, since cy.route() allows it ref: Accessing Fixture Data
e.g the following should be valid, but does not allow setting headers
cy.fixture('test_create').as('create_test')
cy.request('POST', 'http://localhost:8080/widgets', '#create_test');
So, you can use then()
cy.fixture('test_create').then(myFixture => {
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: myFixture,
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
});
or
cy.fixture('test_create').as('create_test');
... // some other code between
cy.get('#create_test').then(myFixture => { // retrieve the fixture from alias
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: myFixture,
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
})
I am using the serverless framework to deploy my lambda to AWS and have been able to successfully run POST requests via Postman to the API Gateway associated with my lambda function, but when I try run a POST request from a form submission (AJAX request) on a local server I am receiving the 502 error message,
Access to XMLHttpRequest at 'https://*id*.execute-api.us-east-1.amazonaws.com/prod/message' from origin 'http://localhost:2368' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
which I didn't expect since I have the cors property in my serverless.yml set to true, which sets CORS configurations for the HTTP endpoint. Here is the function yaml setup:
functions:
email:
handler: handler.sendEmail
events:
- http:
path: message
method: post
cors: true
Here is the jQuery AJAX request:
$.ajax({
type: 'POST',
url: 'https://*id*.execute-api.us-east-1.amazonaws.com/prod/message',
crossDomain: true,
data: JSON.stringify(formData),
contentType: 'application/json',
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
}
});
Is there something that I need to adjust with the API Gateway configuration or within my Lambda application?
Here is my response function:
const generateResponse = (body, statusCode) => {
console.log("generateResponse")
console.log(body)
return Promise.resolve({
headers: {
"access-control-allow-methods": "POST",
"access-control-allow-origin": "*",
"content-type": "application/json",
},
statusCode: statusCode,
body: `{\"result\": ${body.message}}`
});
};
Also provided is the ajax request:
$.ajax({
type: 'POST',
url: 'https://*my-lambda-id*.execute-api.us-east-1.amazonaws.com/prod/message',
crossDomain: true,
data: JSON.stringify(formData),
contentType: 'application/json',
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
}
})
And the resulting OPTION and POST Request and Response Headers triggered by the AJAX:
OPTIONS:
Request URL: https://*my-lambda-id*.execute-api.us-east-1.amazonaws.com/prod/message
Request Method: OPTIONS
Status Code: 200
Response Headers
access-control-allow-credentials: false
access-control-allow-headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent
access-control-allow-methods: OPTIONS,POST
access-control-allow-origin: http://localhost:2368
content-length: 1
content-type: application/json
date: Tue, 08 Oct 2019 11:11:36 GMT
status: 200
via: 1.1 *id*.cloudfront.net (CloudFront)
x-amz-apigw-id: *id*
x-amz-cf-id: *id*
x-amz-cf-pop: *id*
x-amzn-requestid: *id*
x-cache: Miss from cloudfront
Request Headers
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:2368
Referer: http://localhost:2368/
Sec-Fetch-Mode: no-cors
POST
Request URL: https://*my-lambda-id*.execute-api.us-east-1.amazonaws.com/prod/message
Request Method: POST
Status Code: 502
Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json
Origin: http://localhost:2368
Referer: http://localhost:2368/
Sec-Fetch-Mode: cors
Wherever you return a response from your Lambda function you need to include the specific header CORS requests. The cors: true option you add to serverless.yml only helps make sure that the OPTIONS pre-flight requests work. Don't forget that this includes non-success responses as well.
For example:
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': 'Authorization'
}
}
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 });