axios request getting blocked | Reactjs - javascript

I am trying to hit an endpoint in my reactjs code using axios but the request is getting blocked and I am getting the following error in my console.
Please suggest how to overcome this
Below is my code
import * as React from 'react';
import axios from "axios"
export default function App()
{
return (
<>
<button onClick={fetchdata}>Click Me</button>
</>
)
}
function fetchdata()
{
const axios = require('axios');
// Make a request for a user with a given ID
return axios.get('https://randomuser.me/api')
.then(response => {
// handle success
console.log(response);
return response;
})
.catch(error => {
// handle error
console.log(error);
})
}

The reason you're getting this error is because https://randomuser.me expects request from secured origin using https protocol and localhost by default does not runs over https. If this is not satisfied it will be returned as a warning/error by your browser.
However, if you have generated React Project using create-react-app then you can add following script in your package.json:
"proxy": "https://randomuser.me"
Please refer document of Create React App for more details.

It's working fine, please check here
Codesandbox: https://codesandbox.io/s/muddy-dust-yvotv?file=/src/App.js
sometimes this error coming because you started any plugin/extention of cors in your browser

Related

Fetch-request from React frontend doesnt work

I am making a simple program with a backend in ASP.NET Core Web API, and a frontend in JS React. I have a SQL-database in my backend with a table called Events (Arrangementer in Norwegian). The events table has three columns: ID, name, and description.
I have opened and started the react-project. In my App.js (which is the only file I have edited since opening the project), I am trying to fetch some event data from my SQL-database. When I try to console.log() the json-response, nothing gets outputted to the console. I have tried using an ASYNC function, but that doesnt work either. My backend is up and running, and I have data inside of the tables, i can see that when i click the fetch-url.
Here is the App.js file:
import logo from './logo.svg';
import './App.css';
import {useEffect, useState} from 'react'
function App() {
useEffect(() => {
fetch("https://localhost:7031/api/Arrangements")
.then((res) => res.json())
.then((json) => {
console.log(json)
})
}, [])
return (
<div className="App">
<header className="App-header">
testing project
</header>
</div>
);
}
export default App;
The getter in the Swagger UI
I believe something is wrong with the endpoint. First thing that strikes me is that the url you are using starts with https:// but adresses localhost. I'm aware that's possible, but are you sure it's not http:// ?
To be sure of that, please test your endpoint using Postman or the Chrome Dev tools network tab - both should give you sufficient information about the status of your endpoint.
Your frontend code looks good and should work, so I believe you have a backend problem.
Try it plz. Seems your code is fine. If your get response from Backhand(200 in Network Tab) no issues.
import React from 'react';
import { useState,useEffect } from 'react';
const MyApp = () => {
const [service, setService] = useState({})/According to Your API response;
useEffect(() => {
const url = "http://localhost:7031/api/Arrangements";
fetch(url)
.then(res =>res.json())
.then(data => setService(data));
}, [])
return (
<div>
<p>{service.length}</p>
</div>
);
};
export default MyApp;
If you console log the res, you will see some response.
But I don't think you can use JSON in the last .then, because res.json() doesn't save your data anywhere.
Try using a useState, and set that state in the last .then.

Uncaught (in promise) API <api_name> does not exist

I'm trying to add existing backend to a new react frontend. Every time I call the API from react i get,
Uncaught (in promise) API api3ceaf69c does not exist
Client side code
function getData() {
const apiName = "api3ceaf69c";
const path = "/users";
const myInit = {
headers: {},
};
return API.get(apiName, path, myInit);
}
(async function () {
const response = await getData();
console.log(JSON.stringify(response));
})();
index.js
import { Amplify, API } from "aws-amplify";
import awsExports from "./aws-exports";
Amplify.configure(awsExports);
API.configure(awsExports);
aws-exports.json
{
"aws_cloud_logic_custom": [
{
"name": "api3ceaf69c",
"endpoint": "https://xxxxxxx.execute-api.ap-south-1.amazonaws.com/dev",
"region": "ap-south-1"
}
]
}
"aws-amplify": "^4.3.27"
Error
Error screenshot
I went through multiple answers around the same issue but none of them are working for me.
Interestingly this exact same code was working a few days back until I had to rebuild my backend due to some changes.
I thought client code used aws-exports.js to decide if the API exists. Looks like you may have checked it already. Does the xxxxxxx API from your exports file show up in the API Gateway in AWS Console? Can you invoke it from the console?
I figured out the problem finally! Issue was at the place where I'm calling Amplify.configure(aws_exports).
For some reason aws exports was not getting initialized in index.js file so I moved it closer to where I am actually calling the api, i.e. getData() function. It started working post that.

Nuxt.Js axios not using baseURL despite it being set correctly

I want to call an API in asyncData()
async asyncData({ $axios, params, store }) {
let itemUUID = params.item;
let item = await $axios.get("/item/" + itemUUID);
return {item};
}
Problem: Axios is still making the request on http://localhost:3000
if I do a console.log($axios.defaults.baseURL) the correct baseURL of my API is printed.
This also works if I use my store action & make the call by using this.$axios
I am using #nuxtjs/axios 5.13.1 with Nuxt 2.15.6 in SSR mode and configured it with the correct baseURL in the nuxt.config.js
Interestingly, if I edit my page content and a hot module reload is triggered, the correct URL is used. Maybe the question should be if Axios is triggered in the right time, on the server?
Edit: I checked the request that was made on HMR and this was triggered in the client.js.
If I call my store inside the created() hook the request gets executed successfully.
My nuxt.config.js:
publicRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL,
}
},
I'm not sure what is the NODE_TLS_REJECT_UNAUTHORIZED=0 thing doing but your frontend configuration (Nuxt) is working well so far.
Sorry if I cannot help on the Express part.
Maybe try to setup HTTPS locally on Nuxt: How to run NUXT (npm run dev) with HTTPS in localhost?
TLDR; This was not related at all - I forgot to set the auth token for my backend. At the time of axios init it's not present. $axios object doesn't have auth - backend fails.
On page load the nuxt function nuxtServerInit() is used to get the auth token out of the acces_token cookie.
I am using a plugin to initialize Axios - with the token from the store.
But of couse the token is not present at the time axios is initialized as nuxtServerInit is called after plugin init.
In my axios.js plugin I changed:
export default function({ app, error: nuxtError, store }) {
const token = const token = store.state.user.token;
app.$axios.setToken(token, "Bearer");
}
to;
export default function({ app, error: nuxtError, store }) {
const token = app.$cookies.get("access_token");
app.$axios.setToken(token, "Bearer");
}
Now the token is present & used for every request happening server-side.

SWR not returning any data

I'm trying to get SWR to work. Every example I have found doesn't seem to work when i apply it to my code. I'm not sure what i'm doing wrong the code appears to be the same, i'm sure something super simple that i just can't see.
I have a boilerplate next.js app.
my index.js has;
import useSWR from 'swr'
export default function Home({ isConnected }) {
const { data, error } = useSWR('/api/')
return() //jsx here
}
when i start the development server up it tells me http://localhost:3000 is where the development server can be viewed. when i debug and pause in the on the return line it tells me that data and error are undefined. when i go to http://localhost:3000/api/ i get well formed json back(firefox renders it as json).
You need a method to make the request, for you case, it could be like:
import useSWR from 'swr'
import axios from 'axios';
export default function Home({ isConnected }) {
const fetcher = async () => {
return await axios.get('http://mipage/some/');
};
const { data, error } = useSWR('/api/', fetcher)
return() //jsx here
}

Next.js hangs while setting initial props on server-side

I am trying to set up SSR with Nextjs.
I have following code, where I am fetching json data and binding them as initial props.
When I am in development mode all works correctly, when I deploy to the server fetching works only on client-side (when I navigate from other view).
If I try to load directly the page with fetching, server hangs, no error.
I should add that all is running inside Docker container, but I guess it should not matter at this case.
Here is code
import React from 'react'
import { get } from 'axios'
import Layout from '../components/Layout/Layout'
import WorkSingle from '../components/Work/WorkSingle/WorkSingle'
import DocumentTitle from '../hoc/DocumentTitle/DocumentTitle'
const Work = (props) => {
let works = 'Loading...'
if (props.workData.length > 0)
works = props.workData.map(work => (
<WorkSingle
img={work.image}
url={work.url}
title={work.title}
key={work.title}
/>
))
return (
<Layout>
<DocumentTitle title='Some page title' />
<section id="work">
<h1 className="font_title">WORK</h1>
<div className="row">
{works}
</div>
</section>
</Layout>
)
}
Work.getInitialProps = async () => {
const response = await get('VALID_URL')
if (response && response.data)
return { workData: response.data.work }
return {}
}
export default Work
I have solved it, problem was that i wanted to fetch static data from the same server which is serving app, for some reason when server tried to fetch from itself it stuck, I put the resource I am fetching to another server for now and it solved problem.
I was mocking the data via static .json file, I guess when I create actual API endpoint it will work from the same server too.

Categories