React axios - calling a http endpoint from https webapp - reactjs

am trying to call a http endpoint from my react web application created using create react app
i am given the below code and a local pem file
caCrt = fs.readFileSync('./ca-crt.pem')
const httpsAgent = new https.Agent({ ca: caCrt , keepAlive: false })
axios.get(url, { params: params, httpsAgent: httpsAgent {color:#0747a6}}) .then( res =>
not sure how i can call it properly from frontend (https web app), i received several "mixed content" error from chrome, understand that i may not be able to use "fs" module from my react app

Related

Cookies not set on deployed React app on AWS S3

In NestJS i created backend for my app and i used ReactJS for frontend. When i was testing on localhost everything was working fine.
Then i wanted to try and learn some AWS and i made docker image of my backend and deployed it to EC2. After that i got this url:
http://ec2-<SomeNumbers>.<SomeRegion>.compute.amazonaws.com:8080. If i use this url in Postman and do a POST to my login it works fine. I get back JWT as HttpOnly cookie. In my ReactJS app i replaced localhost links with this new link.
I uploaded my ReactJS app to AWS S3 and got this url http://<bucketName>.s3-website.<Region>.amazonaws.com. If i open this it shows correct first page. The problem comes when i fill login form and click login button the JWT cookie is not set so i get Unauthorized.
I really do not know is the problem in my backend, frontend or in AWS settings.
NestJS controller login function:
async login(
#Body() body: LoginUserDto,
#Res({ passthrough: true }) response: Response,
) {
const data = await this.authService.login(body);
response.cookie('jwt', data, { httpOnly: true });
return 'success';
}
ReactJS code:
const api = axios.create({
baseURL: "http://ec2-<SomeNumbers>.<SomeRegion>.compute.amazonaws.com:8080",
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
});
Thanks!

React App, Express Server - Set cookie not being stored in browser

The long short is...
My express backend sets a cookie and sends it back to the client, everything works great when I use Postman and my React Native app. The issue is the web version which is done via ReactJs makes the same request but cookie is stored in the browser.
So I know cookies are working but not for the web version which is strange when I created a test endpoint http://localhost:3000/server and call it straight from the browser the cookie is stored.
So this is my code doing a simple fetch to the server which then sends back a cookie:
const fetchData = async () => {
try {
const res = await fetch(`http://192.168.0.11:3000/server/`, {
credentials: "include",
});
if (res.ok) {
const resData = await res.json();
console.log({ resData });
}
} catch (err) {
console.log({ err });
}
};
The request came back successful but no cookie is stored
Access the same endpoint from the browser directly results in this:
An extract from the response header while being sent shows that the cookie was sent in the response just not stored in the frontend
Was a pretty simple fix
I was using http://localhost:3001 for the react app I just simply used the ip address instead http://192.168.0.11:3001

Making a delete request using Axios to Laravel API throws an error but works fine in insomnia

Hi I am creating a web app using create-react-app which consumes endpoints developed in laravel 5.
When I make a Delete request using axios to the server, I get this error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/carts/7?api_token={api_token}. (Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’) Whereas, when I send the same request on Insomnia (HTTP Rest Client), I donot get any error.
Here is the react code
handleDelete = ( cartId ) => {
const api_token = localStorage.getItem('jbs_user_api_token');
console.log("Delete cart item: ", cartId);
axios.delete(`carts/${cartId}?api_token=${api_token}`)
.then( res => {
console.log(res);
})
.catch( err => {
console.log(err);
});
}
Following is the endpoint in Laravel 5, the react app is making the aforementioned request to
Route::resource('carts', 'API\CartAPIController');
Here is the method (laravel) that handles the delete request
public function destroy($id)
{
$cart = $this->cartRepository->findWithoutFail($id);
if (empty($cart)) {
return $this->sendError('Cart not found');
}
$cart = $this->cartRepository->delete($id);
return $this->sendResponse($cart, __('lang.deleted_successfully', ['operator' => __('lang.cart')]));
}
Definitely, there is no error on the API (Backend) since the request works fine in insomnia. Plus both the applications (react and laravel) are served from localhost.
Please help
In your package.json file of frontend/client folder try to add proxy like this
"name": "app_name",
"proxy": "http://127.0.0.1:8000"
The issue is resolved by adding Laravel Cors package in the laravel App (API Provider).
Following is the link to Laravel Cors pakage
https://github.com/fruitcake/laravel-cors

why does react.js when upload file return cors

const formData = new FormData();
formData.append("CustomerName", this.state.customerName);
formData.append("Email", this.state.email);
formData.append("Phone", this.state.phone);
formData.append("PageNumber", this.state.pagesNumber);
formData.append("Notes", this.state.notes);
formData.append("WritingConversionTypeId", this.state.writingConversionTypeId);
formData.append("WritingDocumentTypeId", this.state.writingDocumentTypeId);
formData.append("WritingTimePeriodId", this.state.writingTimePeriodId);
formData.append("files", 'null');
writingRequest.postwritingRequest(formData).then((res) => {
console.log(res);
});
when attach to headrs form data it return CORS
i'm using react.js and server side ASP.NET Core3.1...
and it works when removing the (Content-Type: multipart/form-data) from headers
it works in swagger
enter image description here
in
at React Service to Call Api
import http from "../../config/http";
import endPoints from "../endPoints";
const writingRequestUrl = endPoints.WRITING_REQUEST_ENDPOINT;
export default {
postwritingRequest(writingRequest) {
return http
.post(
writingRequestUrl,
writingRequest
, {
headers: {
'enctype': 'multipart/form-data',
"Content-Type": "multipart/form-data"
},
}
)
.then((res) => {
return res;
});
},
};
In StartUp
At ASP.NET CORE
ConfigureServices
//Enable CROS To allow access to the resource
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
}));
In Configure
app.UseCors("MyPolicy");
CORS has nothing to do with react, your browser prevents the call as the client runs on a different domain than your server. On production this is usually not an issue, since both are typically running on the same domain.
If you want to avoid CORS in development, the Create React App bundle comes with a proxy server, that appends the CORS header to all HTTP requests, as described in the documentation.
Simply add the URL to your api to your package.json like so:
"proxy": "www.url-to-your-api.com"
Then make sure to run all requests from your react app against absolute links, so instead of calling www.url-to-your-api.com/api/ you should simply use /api/, this will use the proxy in development and the regular route in production.

How to add custom HTTP headers in React application?

I have a react js application. I want to add some http headers in the every response that's being returned from the app. Could you please suggest how to implement this !
NOTE : I am not trying to call any api with headers in request. I want my react app to respond with some custom headers in the response
As Dovlet Mamenov mentioned in the comment, this has to be done on the web server wherever react app is hosted.
For example, If react app is hosted on the Apache server, then these http headers in the response should be added on the Apache server conf.
const header = new Headers();
header.append('Access-Control-Allow-Origin', '*');
const body = {
author: author,
text: text
}
axios.post("https://api.test/posts/create", body, header)
.then((res) => {
this.setState({
result: res
});
})
.catch((error) => {
this.setState({
error: error.message
});
})
You have to use the native object Headers, and add it in axios.

Resources