I wrote these http cookie functions in Go as a part of a http handler that will respond to ajax calls.
cookie = &http.Cookie{
Name: "sessionId",
Value: "",
}
http.SetCookie(w, cookie)
However, I need to set my writer header to JSON as the ajax caller expects JSON response
jsonResponse, _ := json.Marshal(responseMessage) //responseMessage is a struct
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, "%s", jsonResponse)
The cookie is not set to the browser. Everything is on the same domain (no CORS). How can I send JSON with cookie data to an ajax caller together in Go?
Related
For some reason, when I send JSON formatted data through Postman as raw text, I have no issues. When I send the exact same data through Postman as raw JSON (the difference should only be that the content-type header is application/json instead of application/text), I end up with my double quotes stripped and my strings switched to single quotes.
Original payload example (Postman sends this):
{ "id": "blahblahbloo", "time": "hammer" }
Unintended transformation (NextJS receives this):
{ id: 'blahblahbloo', time: 'hammer' }
To be clear, I get the exact same thing (which is what I expect) when I send as raw text via Postman:
// Postman sends this and NextJs receives this when set to raw text
{ "id": "blahblahbloo", "time": "hammer" }
I'm not explicitly doing anything to read the content-type and transform the data. My endpoints with this issue is a NextJS Dynamic Route: https://nextjs.org/docs/api-routes/dynamic-api-routes
Next.js API routes have a built-in bodyParser middleware that will parse the incoming request's body based on its Content-Type header.
From the API Middlewares documentation (emphasis is mine):
API routes provide built in middlewares which parse the incoming
request (req). Those middlewares are:
req.cookies - An object containing the cookies sent by the request. Defaults to {}
req.query - An object containing the query string. Defaults to {}
req.body - An object containing the body parsed by content-type, or null if no body was sent
Sending the payload as application/json will have the API route convert the req.body to a JavaScript object, hence striping the double-quotes.
While the bodyParser middleware is automatically enabled by default, you can disable it if you want to consume the body yourself.
// In the API route
export const config = {
api: {
bodyParser: false
}
}
When sending a post request cookie param is getting set in request header.
Is there any way to stop sending cookie param in api request header for a particular api call in angular interceptor
http module by default does not set the cookie params. When you get the response, http module discards the cookie and does not add it in the follow up requests. So you have add it manually:
checkAuth() {
// if we did not add { withCredentials: true }, response would be false becasue, cookies wont be attached
return this.http.get<SignedinResponse>(this.rootUrl + '/signedin',{withCredentials:true}).pipe(
tap(({ authenticated }) => {
// console.log('response from /signedin', res);
})
);
}
you have to add {withCredentials:true} this to each request manually. instead we write interceptor, to modify the req obj and add the cookie by default.
I have a problem in sending web service request using Delphi 7 and Indy. My workplace a public hospital as a client and insurance third party as the server. Here is the service catalogue:
URL : {BASE URL from the insurance office}/Delete
Method : DELETE
Format : Json
Content-Type: Application/x-www-form-urlencoded
Request body :
{"request": {"t_obj": {"noObj": "0301X1018V001","user": "myUser"}}}
I use Indy 10.6 and some of the code I wrote is:
Json := '{"request": {"t_obj": {"noObj": "0301X1018V001","user": "myUser"}}}';
req := TStringStream.Create(Utf8Encode(Json));
resp := TStringStream.Create('');
IdHttp1.request.Source := req;
IdHttp1.Request.ContentType := 'Application/x-www-form-urlencoded';
IdHttp1.delete('{BASE URL from the insurance office}/Delete', resp);
showmessage(resp.DataString);
But, when the request sent, it failed to delete.
Any one can help me, please? I'm sorry my English is not good enough.
Thank you.
Application/x-www-form-urlencoded is not a valid media type for sending JSON. Are you sure the server is not actually expecting application/json instead? It should be.
Beside that, a more important reason why your request does not work is because the TIdHTTP.Delete() method simply does not allow sending a post body, so the server never sees the JSON at all. Internally, Delete() calls the TIdCustomHTTP.DoRequest() method passing nil in the ASource parameter, which replaces your assignment of the TIdHTTP.Request.Source property.
To do what you are attempting, you will have to call DoRequest() directly, eg:
// TIdCustomHTTP.DoRequest() is protected,
// so use an accessor class to reach it...
type
TIdHTTPAccess = class(TIdHTTP)
end;
...
Json := '{"request": {"t_obj": {"noObj": "0301X1018V001","user": "myUser"}}}';
req := TStringStream.Create(UTF8Encode(Json));
try
resp := TStringStream.Create('');
try
//IdHttp1.Request.Source := req;
//IdHttp1.Request.ContentType := 'Application/x-www-form-urlencoded';
IdHttp1.Request.ContentType := 'application/json';
//IdHttp1.Delete('{BASE URL from the insurance office}/Delete', resp);
TIdHTTPAccess(IdHttp1).DoRequest(Id_HTTPMethodDelete, '{BASE URL from the insurance office}/Delete', req, resp, []);
ShowMessage(resp.DataString);
finally
resp.Free;
end;
finally
req.Free;
end;
I'm trying to send JSON arguments to my server and parse them using json.Decoder. I've read that you should be able to get the query params from the request.Body property. The following is my server code:
func stepHandler(res http.ResponseWriter, req *http.Request) {
var v interface{}
err := json.NewDecoder(req.Body).Decode(&v)
if err != nil {
// handle error
}
log.Println(v)
}
Every time, I see 2014/12/26 22:49:23 <nil> (diff timestamps, of course). My client-side AJAX call is the following:
$.ajax({
url: "/step",
method: "get",
data: {
steps: $("#step-size").val(),
direction: $("#step-forward").prop("checked") ? 1 : -1,
cells: JSON.stringify(painted)
},
success: function (data) {
painted = data;
redraw();
},
error: function (xhr) {
console.log(xhr);
}
});
An example URL of what is sent:
http://localhost:5000/?steps=1&direction=1&cells=%5B%7B%22row%22%3A11%2C%22column%22%3A15%7D%2C%7B%22row%22%3A12%2C%22column%22%3A15%7D%5D
A nicer look at the params:
{
steps: "1",
direction: "1",
cells: "[{"row":11,"column":15},{"row":12,"column":15}]"
}
I have tried with both GET and POST requests.
Why does my req.Body never decode? If I try to print req.Body alone, I also see nil.
req.Body is indeed empty -- so, what I would do it call req.ParseForm() and then use req.Form instead. Body will not get stuff (such as, query parameters) that's definitely not in the request's body.
The Body of a request is sent along inside the payload - it is not part of the URL.
You're attempting to access the body .. when really your data is in the URL.
What you want it to change your ajax method: "get" to be method: "post" - so that the data is posted along with the body and not as part of the URL. You should also make sure that the data is indeed being sent along with the request via your browser of choice' developer tools. Alternatively, if you really do want your data sent along as part of the URL, you should be accessing the URL parameter of the request - and manually parsing the values into a struct (the json package won't do this for you IIRC).
Can anyone share an end to end example for making a JSON webservice Call Through Apex ( Visual Force Pages and Controllers ) in Salesforce .
Pretty Much like we do in HTML5 ,Jquery by Ajax !
There are examples right in the documentation of calling REST web services.
From HTTP Classes:
public class HttpCalloutSample {
// Pass in the endpoint to be used using the string url
public String getContent(String url) {
// Instantiate a new http object
Http h = new Http();
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
return res.getBody();
}
}
You can change the method to one of:
GET, POST, PUT, DELETE, TRACE, CONNECT, HEAD, and OPTIONS
A more complete example is available at HTTP (RESTful) Services
There is also support for JSON deserialization.
Don't forget to use the Remote Site Settings to open up access to the target domain.
For a SOAP web service you can define Apex classes from a WSDL.