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.
Related
I want to make a recipes website and got the API key from spoonacular. when I run the website it says I have unauthorized access. I tried canceling and restarting the npm, flushing my DNS, clearing my cache, restarting my computer, and generating a new key, i even deleted the application and rewrote the code but nothing seems to work.
I'm using vs code.
here's the code:
import React from 'react'
import {useEffect} from "react";
function Pop() {
useEffect(() => {
getPop();
},[]);
const getPop = async() =>{
const api = await fetch(`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_KEY}&number=9`);
const data = await api.json();
console.log(data);
}
return (
<div>Pop</div>
)
}
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
}
My error occurs when I try to send api requests with axios but do not see the same error sending the request with fetch. I looked at several react-native applications and It looks like I am using the axios.get method similar to theirs and don't see what I am doing wrong. I am new to react native so maybe I am doing something naively.
import React from 'react'
import {
View,
Button
} from 'react-native'
import axios from 'axios'
const Example = () => {
const requestGoogle = () => {
const url = 'https://google.com'
axios.get(url) //fetch(url) no error
.then(res => {
alert(res)
})
.catch(err => {
alert(err)
})
}
return ( <
View >
<
Button title = "Send"
onPress = {
() => requestGoogle()
}
/> <
/View>
);
}
export default Example
I get the following error when running the previous code:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
Looking into each reason:
I confirmed that React and React Dom have same react version 16.13.1
I don't think I but maybe?
I confirmed that only one copy of app exists in the project following their steps
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
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.