How do I access the Response Headers using ServiceStack - javascript

I'm using react with Redux toolkit but I'm unbale to access the Response headers
return await client
.get(new Users())
.then((data) => {
// how to I access the Response Header here?
console.log("data", data);
return data;
})
.catch((error) => {
});

I'm assuming you're referring to ServiceStack's TypeScript Service Client, the public API of which you can find on index.d.ts where you can use the instance requestFilter and responseFilter:
export declare class JsonServiceClient {
//...
requestFilter: (req: IRequestInit) => void;
responseFilter: (res: Response) => void;
}
To inspect the underlying W3C fetch API's Request / Response, e.g:
let client = new JsonServiceClient();
client.responseFilter = function(r) {
console.log(r.headers)
}
client.get(new Users())
.then(...)

Related

CORS Missing Allow Origin error .NET Core API when trying to fetch data

I'm new to web programing and am trying to fetch user data from a .NET Core API using JavaScript but I have been getting a CORS Missing Allow Origin error. I'm aware that this is probably a common and easy issue to resolve but I haven't been able to figure out how to do so. And as mentioned in similar questions I also tried it with the " withCredentials: true" configs for the fetch.
I don't even know at this point whether the issue is server or client side. Could anyone point me in the right direction?
JavaScipt
function ApiController({id}){
const [user, setUser] = useState({});
useEffect(() => {
axios
.get('https://localhost:7278/User/' + id, {
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json'
}
})
.then(res => {
console.log(res);
})
.catch( err => {
console.log(err);
})
}, [id]);
UserController.cs
//------------------------------------------------------------------------------
/// <summary>The user controller.</summary>
[Route("[controller]")]
[ApiController]
public class UserController : ControllerBase {
/*
...
*/
[HttpGet("{userId}")]
public async Task<UserDto> GetUser(Guid userId) {
return await _userService.GetUser(userId);
}
Startup.cs
/*
...
*/
services.AddCors(options => {
options.AddDefaultPolicy(builder => {
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
/*
...
*/
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyHeader()
);
CORS is configured through server-side, so you need to configure on your Server.
Please make sure you enable CORS on the server side, please refer to Enable Cross-Origin Requests (CORS) in ASP.NET Core for configuration method.
I did a test on this and your problem didn't appear:
JavaScript(refer to this document):
const uri = 'https://localhost:44336/WeatherForecast';
function getItems() {
fetch(uri, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin': '*'
}
})
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get items.', error));
}
Then, register CORS on the called server side.(refer to this document).
Result:
If the problem persists, you can try passing Access-Control-Allow-Origin from the server's response:
app.Use((context, next) =>
{
context.Response.Headers["Access-Control-Allow-Origin"] = "*";
return next.Invoke();
});
Hope this can help you.

My express.js is not receiving the body that I sent from react native

I have a api object set up like this in react native:
import axios from "axios";
import AsyncStorage from "#react-native-async-storage/async-storage"; //npm install #react-native-async-storage/async-storage
const instance = axios.create({
baseURL: "localhost url here",
});
/**
* This will add a header if we have a token only,
* we will be adding a Authorization header to our instance before running
* the http req
*/
instance.interceptors.request.use(
//this will be called before doing the http request,
//it is async because to retrieve the storage it is async
async (config) => {
const token = await AsyncStorage.getItem("token"); //awaits until it gets token (IF THERE IS ONE)
//if there is a token
if (token) {
config.headers.Authorization = `Bearer ${token}`; //add string 'Bearer withGivenTOKEN'
}
return config;
},
(err) => {
return Promise.reject(err);
}
);
export default instance;
When doing the api call I am doing this:
await myApi
.get("/routeHere", {
latitude: currentLocation.latitude,
longitude: currentLocation.longitude,
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
When receiving the data the body part is just a an empty object. Is there a reason why this happens? Am I doing something wrong?
router.get("/routeHere", async (req, res) => {
console.log("here is my body: ", req.body);
}
I think I'm missing to add the header type, but not sure if it will work, and if it is, how can you write it? I'm new to express and react native
GET request shouldn't include data.
The HTTP GET method requests a representation of the specified resource. Requests using GET should only be used to request data (they shouldn't include data).
GET method
But you can use params to send the latitude and the longitude, like this:
await myApi
.get(`/routeHere?latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}`)
.then((response) => console.log(response))
.catch((err) => console.log(err));
or
await myApi
.get("/routeHere", {
params: {
latitude: currentLocation.latitude,
longitude: currentLocation.longitude,
}
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
And you can receive it in the backend with req.query.latitude and req.query.longitude

Is there a difference in data/promise returned from axios get and post?

I'm working on a React application that makes use of an imported object with a get request to an api and a post request to a related API.
When creating a new instance of my service in the frontend in React, I am able to successfully use the '.then' & '.catch' functions to access the returned data ONLY from the get request.
When using the post request from the same object, when trying to access the response object, I get a (paraphrased) '.then' is not a function on undefined.
Only when I explicitly write out the post request in my form submit function (without consuming a service) and handling the object there am I able to check the response and subsequently set the state.
What is the appropriate/best practice way for using axios in React and why am I not able to access the response object when I create a new instance of a service?? Much appreciated!
Service:
import axios from 'axios';
class ProductServices {
getAllProducts(){
return axios.get('https://somecustomAPIURL')
}
postProduct(somePathConfig){
axios.request({
url: 'https://somecustomAPIURL' + somePathConfig,
method: 'post',
headers: {'some-custom-header': process.env.REACT_APP_API_POST_KEY}
})
}
}
export default ProductServices;
React Code instantiating and consuming the service (note, that getAllProducts works just fine, but trying to consume a response object in postProduct returns an '.then' is undefined)
constructor(){
super();
this.state = {
products: [],
productID: null,
showModal: false
}
this.ProductServices = new ProductServices();
}
getAllProducts = () => {
this.ProductServices.getAllProducts()
.then((response) => {
let items = response.data.data.items;
this.setState({
products: items,
productID: items[0].id
});
return response;
})
.catch((error) => {
console.log('Error!', error);
return error;
})
}
handleFormSubmit = (e) => {
e.preventDefault();
let productID = this.state.productID;
this.ProductServices.postProduct(productID)
.then((response) => {
this.setState({showModal: true}, () => console.log('Success!'));
return response;
})
.catch((err) => {
console.log('Error!', err);
})
}
You missed return before axios.request.
import axios from 'axios';
class ProductServices {
...
postProduct(somePathConfig){
return axios.request({
url: 'https://somecustomAPIURL' + somePathConfig,
method: 'post',
headers: {'some-custom-header': process.env.REACT_APP_API_POST_KEY}
})
}
...
Also, instead of axios.request, you can use axios.post like axios.get
return axios.post(url, body, { headers });
return axios.get(url, { headers });
return axios.put(url, body, { headers });
return axios.delete(url, { headers });
return axios.request(axiosConfigOptions);

POST - Angular 5

I'm fairly new to angular and got stuck at getting data from SpringREST which is at backend.
So scenario is:I'll be getting a JSON string from backend as POST(JSON data will be redirected to my hosted link of site as POST) and I need to catch that JSON string and display it on UI.
I'm not sure about the postMethod in dataservice.ts if it should be there.
I googled on stackoverflow and came up with below code which doesn't seem to work in my scenario:
Component.ts
import { MyDataService } from './services/my-data.service';
constructor(private posting: MyDataService
) {}
ngOnInit() {
this.posting.postMethod().subscribe(
(response => {
console.log(response)
}));
}
}
Data-service.ts
#Injectable()
export class MyDataService {
constructor(private http: Http)
{ }
postMethod(model: any ) {
return this.http.post("http ://", model)
.map(res => res.json());
}
}
As the error says, You need to pass the parameter to the service when invoking
this.posting.postMethod(model).subscribe(
(response => {
console.log(response)
}));
As i can see in your component.ts you are not passing the model as a parameter.
you need to pass the model as a parameter.
this.posting.postMethod(anyData).subscribe(
(response => {
console.log(response)
}));
If this is not the issue then please update us with the error you are getting.
This is the right way to define a function in the subscribe method:
ngOnInit() {
this.posting.postMethod(model).subscribe(
(response) => {
console.log(response)
});
}

Check Axios request url before sending

API requests are failing because the URL generated by Axios is incorrect due to my config. I know what the request url is suppose to look like, so I want to see the request url Axios generates.
I can point Axios to my local server and see the requests there, but I want to debug this on the client. I want to play with the config, and see how the requests change. Is there a way to output the request url from Axios before or after sending?
// param format
{ address: 'Vancouver', key: GOOGLE_API_KEY }
// Geocode sample
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY
_request = async (...args) => {
const { outputFormat, params } = args
const instance = axios.create({
baseURL: `https://maps.googleapis.com`,
})
const response = await instance.get('/maps/api/geocode/${outputFormat}?', {
params,
})
// I want to see the url generated by Axios so I can debug the issue
console.log(response)
}
I am within the Expo, React Native environment.
Working example using fetch:
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=vancouver&key=${GOOGLE_API_KEY}`
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data)
})
.catch(function(error) {
console.log(error)
})
Solution used:
_request = async (obj) => {
const { outputFormat, params } = obj
const instance = axios.create({
baseURL: `https://maps.googleapis.com`,
})
instance.interceptors.request.use(function (config) {
console.log(config)
return config
}, function (error) {
return Promise.reject(error)
})
const response = await instance.get(`/maps/api/geocode/${outputFormat}`, {
params,
})
}
You can turn on debug mode and look at the network tab as mentioned in the other answer, or you can intercept axios and console.log or do whatever you want with the request before it's sent:
axios.interceptors.request.use(function (config) {
// Do something before request is sent
console.log(config)
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
You can just use axios#getUri([config]) (source) to perform the same logic as the request. It merges the configurations (e.g. the given config and the instance configuration), merges the url with the baseURL, and appends any params using the paramSerializer.

Categories

Resources