'How to add as: :json?
I have this .ts file (ruby on rails application), and I have a code like this:
export const create = async (params: CreateRequest): Promise<XYZ> => {
const response = await request<XYZ>(`/api/xyz`, 'post', params);
return response?.data;
};
And I want to make something like this:
export const create = async (params: CreateRequest): Promise<XYZ> => {
const response = await request<XYZ>(`/api/xyz`, 'post', params, as: :json);
return response?.data;
};
And of course, this doesn't work; I'm a noob; please help!
Solution 1:[1]
You can request JSON from a Rails app with the Content-Type=Application/JSON header (and also Accept) just like with any other server. See the documentation for whatever request is for instructions on how add headers.
In Rails you can also set the format by appending an extension onto to the URL (for example '/api/xyz.json') which overrides the headers.
For a Rails API you can/should also set the default request type with something like namespace :api, defaults: { format: :json } do ... in config/routes.rb.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
