Can I add some field into response in restful api of springboot? - spring-boot

I used axios in vuejs and it calls api to spring boot. then the response is as below.
{
status: 200,
statusText: '',
config: [...],
headers: [...],
request: [...],
data: [My response data (ResponseEntity)]
}
I want to add some field in root level, like this.
{
status: 200,
statusText: '',
config: [...],
headers: [...],
request: [...],
data: [My response data (ResponseEntity)],
code: 'MyCode',
message: 'MyMessage'
}
I can't found any information about this.. so please help me to make it.

Related

How/Where does nuxtjs set the authorization header

I inherited a web project from another developer who's left the company. It is built with nuxtjs and laravel, neither of which I am strong with.
In the web project, after a user goes to a login screen, types in email and password, and presses save, I can see in my developer tools that the nuxtjs framework sends a {email: "user#email.com", password: "password"} to the laravel api at https://example.project.com/api/login. The laravel api then returns a 200 response with this payload { data: { message: "Login successful.", token: "50|Fs88RPU7HON1LnBskm35O9txG0OnXDiG3x4XWILJ" }}. Everything is great so far!
Immediately after the 200 response above, NuxtJS sends another request to https://example.project.com/api/auth/user in an attempt to get information about this user. Nginx gives a 401 response. My first suspicion for why this happens is because NuxtJS sent an Authorization: Bearer undefined as shown in this screenshot of my browser dev tools
I've seen other situations with Authorization: Bearer [object object].
I want to know how does NuxtJS decide what value to provide to the Authorization http header? This is my current nuxt.config.js
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'Blah',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.png' }],
},
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
'#nuxtjs/auth'
],
auth: {
redirect: {
login: '/login',
logout: '/',
callback: '/api/login',
home: '/'
},
strategies: {
local: {
endpoints: {
login: { url: '/api/login'},
user: { url: '/api/auth/user'}
},
}
},
localStorage: true
},
proxy: {
'/api': {
target: 'https://example.project.com/',
pathRewrite: { '^/api': '' },
},
},
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
baseURL: 'https://example.project.com/',
credentials: true,
headers : {
common: {
'Accept' : 'application/json'
}
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
}
}
And also, this is the line of code in pages/login.vue that starts the login process:
await this.$auth.loginWith('local', { data: {email:"user#email.com",password:"password"} });
Simply add Authorization header as default header right after authorization request. Assuming that server sends access token in response the code might look like this:
const response = await this.$auth.loginWith('local', {
data: {
email: "user#email.com",
password:"password"
}
})
const { token } = response;
axios.defaults.headers.common = { Authorization: `Bearer ${token}` };
change your strategy as below to set property name of the token being returned in response.
strategies: {
local: {
token: {
property: 'token'
},
endpoints: {
login: { url: '/api/login'},
user: { url: '/api/auth/user'}
},
}
},
It will include the authorization header in all your requests using $axios.
also you might need to set propery of the user which you are returning from backend also.
This is done by a library in the background. #nuxtjs/auth or #nuxtjs/auth-next will set the token depending on your config in nuxt.config.ts.
You can find the token in the local storage in auth._token.<strategy>. To use a Bearer token in the subsequent userinfo request you might need to set:
nuxt.config.ts
auth: {
strategies: {
local: {
token: {
type: 'Bearer',
}
}
}

Can I log to file all the responses made during running cypress test?

When I'm running cypress e2e tests, application makes XHR requests. How can I log all this requests and responses? I don't want to stub these requests. I with to get an artifact with all requests and responses made during test. Gitlab is used as CI.
Main test code looks like this. All these are user defined commands, interacting with the application. Interacting with the application causes different requests to be made (e.g. I click a button, this causes the request).
it('Log response to a file',function(){
cy.request({
method: 'GET',
url: 'https://<site>/home/payments/currency/confirm/*',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((response)=>{
const someResponse = response.body;
console.log("hhhh"+someResponse);
cy.writeFile('cypress/fixtures/testResponse.json', someResponse);
cy.login(login_name, pass)
cy.typeOTPpinpad(secret)
cy.makePayment('Currency', 'amount')
cy.typeToken(secret)
cy.logout()
})
})
Here is how I tried to use regular expression to catch request (id is unique and I need to use regular expressions).
https://<mysite>/home/payments/<currency>/confirm/* - asterisk is payment id.
You could grab the request and response and write to a location as below. I have write the request and response to fixture folder as below: Try the below and let me know
it('Log request to a file',function(){
cy.request({
method: 'GET',
url: 'url_here',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((request)=>{
const someRequest = JSON.stringify(request);
console.log("hhhh"+someRequest);
cy.writeFile('cypress/fixtures/testRequest.json', someRequest);
})
})
// The below is for response:
it('Log response to a file',function(){
cy.request({
method: 'GET',
url: 'url_here',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((response)=>{
const someResponse = response.body;
console.log("hhhh"+someResponse);
cy.writeFile('cypress/fixtures/testResponse.json', someResponse);
})
})
The testrunner has such information on board:
[

How to get errors translated from Laravel with API (use AXIOS)

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 !

Sencha touch2: make Ajax post request for Json data

hi am new to Sencha touch2, am facing problem while fetching data from a remote url. When i use the url in simple rest client am able get data and with status: 200 ok. Here is input of simple rest client for your reference.
---------------
url: http://190.40.2.14:9030/work
Method: post
Headers:Accept: application/json
Data:<workTO><platform>ALL</platform></workTO>
---------------
how can i use post request, headers and data how can i do this in Sencha touch2.
here is the model with proxy:
Ext.define('TestApp.model.myModel', {
extend: 'Ext.data.Model',
xtype:'modelList',
config: {
fields:['work'],
proxy:{
type:'rest',
// url:'http://localhost:9090/TestApp/app/store/sample.json',// this works
url:'http://10.30.2.141:9030/work',
reader:
{
type:'json'
}
}
}
});
Ext.define('TestApp.model.ModelList', {
extend: 'Ext.data.Model',
xtype:'modelList',
config: {
fields:['task'],
proxy:{
type: 'ajax',
url:'http://localhost:9090/TestApp/app/store/sample.json',
callbackKey: 'theCallbackFunction'
},
reader: 'json'
}
});
you json should have relative path, not absolute for ajax to work, cross domain can be achived via JSONP but you need to setup api with callback feature else it wont work

Trigger.io Ajax Requests - with Parse Facebook User authentication

I'm trying to authenticate users from Trigger.io, ideally via Facebook.
I authenticate the user via Facebook (using the Parse Facebook module), and pass their access token, acess expiry date, and facebook Id to my call to Parse.
It is here things go wrong. Whenever I try and post this data via Ajax to the Parse REST API, I get an error in my forge/Trigger console reading:
{ type: 'EXPECTED_FAILURE', content: '{"code":107,"error":"This
endpoint only supports Content-Type: application/json requests, not
application/x-www-form-urlencoded."}', statusCode: '400', message:
'HTTP error code received from server: 400' }
The code I used to try and post this data is...
function auth(facebookId,accessToken,expirationDate) {
forge.logging.log('auth started');
forge.request.ajax({
url: 'https://api.parse.com/1/users',
headers: {
'X-Parse-Application-Id': config.parseAppId,
'X-Parse-REST-API-Key': config.parseRestKey,
'Content-Type': 'application/json'
},
type: 'POST',
dataType: 'json',
data: {
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
},
success: function (data) {
forge.logging.log('auth finished 1');
forge.logging.log(data);
},
error: function(error){
forge.logging.log('auth finished 2');
forge.logging.log(error);
}
})//success
} //auth
I can't figure out how to send this as a JSON object/ in the correct format. If anyone has any ideas they'd be much appreciated. Thanks. Josh.
Whenever the data option passed to forge.requests.ajax is an object like in your example, what actually gets posted is a query string that represents the object. The contentType option merely allows you to set the Content-Type header, it does not effect how objects are encoded for the request.
However if the data option is just a string, then this string is used as the body of the request. You can generate a JSON string to use as the body using JSON.parse like so:
forge.request.ajax({
...
contentType: 'application/json',
data: JSON.stringify({
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
})
});

Resources