How can I return(echo) the requested content-type and body?
mockServer.stubFor(
put(WireMock.urlEqualsTo("/echo"))
.willReturn(
aResponse()
.withStatus(200)
.withHeader("Content-Type", "##?") // same as request.content-type
.withBody("##?") // same as request.body
)
);
Or is there any alternative library that I can do this?
Related
I have a working RTK Query api, reading from a backend that after a successful login was sending the token in the payload.
The backend API changed and now the token comes in the response's Authorization header and I can't figure out how to read it.
This is what I had before, on my reducer. I used a matcher for when the request was fulfilled and stored the token in the payload:
// reducer.js
const authReducer = createSlice({
// ...
extraReducers: (builder) => {
builder.addMatcher(backendApi.endpoints.login.matchFulfilled, (state, { payload }) => {
// save the payload.token in localstorage
}
}
});
It seems like getting the headers is not straightforward, and I actually can't find the Authorization header when trying to get the headers from the request:
// reducer.js
const authReducer = createSlice({
// ...
extraReducers: (builder) => {
builder.addMatcher(backendApi.endpoints.login.matchFulfilled, (state, { meta }) => {
const headers = meta.baseQueryMeta.response.headers; // this is a Headers {} object
console.log(headers.get('content-type')); // prints application/json; charset=utf-8
console.log(headers.get('authorization')); // prints undefined
}
}
});
When I try to debug and print all headers with console.log(Array.from(headers)) this is what I get:
[
[
"cache-control",
"max-age=0, private, must-revalidate"
],
[
"content-type",
"application/json; charset=utf-8"
]
]
It's super strange because the response has many more headers, but I can't access them.
Any guidance here? Maybe it's not possible to read the headers this way?
Thanks in advance!
You are doing everything right there. If headers.get('authorization') comes back as undefined I would assume it is a CORS issue preventing your JavaScript from accessing that.
So your server would need to set the correct CORS headers, nothing to do on the client side.
Good afternoon. Slightly confused in the Gatling documentation, I can not find a solution. I want to get a token to use in another method as a header. Here is an example of the first method where I get a token:
exec(
http("HTTP Request auth")
.post("http://blabla:9001/connect/token")
.header("Content-Type","application/x-www-form-urlencoded")
.formParam("grant_type","password")
.formParam("username", "${login}")
.formParam("password", "${password}")
.formParam("client_id","ro.client")
.formParam("client_secret","secret")
.check(status is 200)
.check(header("access_token").saveAs("access_token"))
.check(header("token_type").saveAs("token_type"))
)
Here's the second method, where I want to pass the token:
.exec(
http("HTTP Request createCompany")
.post("/Companies/CreateCompany")
.header("Authorization","${token_type} + ${access_token}")
.check(status is 200)
)
As a result, writes that a token was not found:
Request:
HTTP Request auth: KO header(access_token).find(0).exists, found nothing
But then he writes:
body={"access_token":"7e8c1d997dd92f16a87fa7ffb8a88ab14eb05a8883d78fe8652d072f24b5ca4a","expires_in":31536000,"token_type":"Bearer"}
I guess I find it wrong here:
.check(header("access_token").saveAs("access_token"))
.check(header("token_type").saveAs("token_type"))
The body of the first request is a Json payload, you need to use jsonPath, which is like XPath for Json:
.check(jsonPath("$.access_token").saveAs("access_token"))
.check(jsonPath("$.token_type").saveAs("token_type"))
Also, the header of the second request will print as:
.header("Authorization", "${token_type} + ${access_token}")
=> Authorization: Bearer + 7e8c1d997dd92f16a87fa7ffb8a88ab14eb05a8883d78fe8652d072f24b5ca4a
Unless you really want the extra +, the right header construction might be:
.header("Authorization", "${token_type} ${access_token}")
One way is to do like this ->
exec { session => var access_token ='' ;
your exec code
session.setAll( "token_type" -> access_token );
}
Then token_type is available to use.
Have a REST application using Slim Framework v3. All works as expected, but I cannot seem to set headers for the response.
For example:
$app->any('/[{path:.*}]', function(Request $request, Response $response, $args = null ) use ( $objError, $objDBCon, $objUtil ) {
...
return $response->withAddedHeader( 'WWW-Authenticate', 'API-key realm="restricted"' )
->withJson($apiResults, $httpcode);
});
Works as expected in terms of getting data, getting the correct http status code, etc.
For example I get a the correct response JSON
{ "message": "You must be logged in to access this resource" }
and I get the expected status code:
Request Method:GET
Status Code:401 Unauthorized
and all the standard, correct headers, content-type, etc, etc.
But cannot seem to set any additional headers.
Reference documentaiton https://www.slimframework.com/docs/objects/response.html
My reputation is to low to add a comment:
According to the manual
withAddedHeader method appends the new value to the set of values that already exist for the same header name
Does your header already exists before appending?
I usually create a new header for each response, something like this:
return $response = $next($request, $response)
->withHeader('Access-Control-Allow-Origin', $this->allowedhosts)
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->withStatus(200);
hope this helps.
I have a Jersey REST interface that I want to send cookies in its responses to each request but no cookies are ever present in any response.
I have a feeling it's a CORS issue and I'm not sure what CORSResponseFilter configuration I need to allow cookies to be set and successfully sent in a response.
My project is built with SpringBoot under Kotlin.
Response code:
#POST
fun put(): Response {
val cookie = NewCookie(Cookie("RESERVATION", "TEST"),
"Session", 60 * 60, false)
return ok()
.cookie(cookie)
.entity(Result("OK", "Success"))
.build()
}
Filter code:
open class CORSResponseFilter : ContainerResponseFilter {
override fun filter(req: ContainerRequestContext?, res: ContainerResponseContext?) {
res?.headers?.add("Access-Control-Allow-Origin", "*")
res?.headers?.add("Access-Control-Allow-Methods", "POST, GET")
res?.headers?.add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
res?.headers?.add("Access-Control-Expose-Headers", "Set-Cookie")
res?.headers?.add("Access-Control-Allow-Credentials", "true")
}
}
Requests are successful and the responses send otherwise as intended but all without any cookies. Prior to setting up the response filter I was able to receive cookies in each response.
Any help is appreciated.
Trying to request cors request with code:
export default Collection.extend({
model: person,
url () {
return 'http://127.0.0.1:5000/person/'
},
ajaxConfig: function () {
return {
headers: {
'Access-Control-Allow-Origin': 'http//:127.0.0.1:3000'
},
xhrFields: {
withCredentials: false
}
};
},
})
I'm sending request with http//:127.0.0.1:3000 but if use * i still get error below
XMLHttpRequest cannot load http://127.0.0.1:5000/person/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
How to handle this kind of request?
Rather than your Collection sending the 'Access-Control-Allow-Origin': 'http//:127.0.0.1:3000' in its request headers, your server at http://127.0.0.1:5000 needs to send it in its response headers to the pre-flight request.
If you can give some details about the server setup, I can help you to figure out how to add the header to the response.