FetchError: request failed - reactjs

I have a bug, i'm trying to make his tutorial for twitter clone in nextjs+tailwindcss+typescript
https://www.youtube.com/watch?v=rCselwxbUgA&t=1357s&ab_channel=SonnySangha
1:42:05 / 3:17:52
I did exactly the same but i feel like my IDE or my nextJS version is making things different
import { Tweet } from "../typings"
export const fetchTweets = async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
FetchError: request to https://localhost:3000/api/getTweets/ failed,
reason: write EPROTO 140020696905664:error:1408F10B:SSL
routines:ssl3_get_record:wrong version
number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:
This error happened while generating the page. Any console logs >will be displayed in the terminal window.
import { Tweet } from "../typings"
export const fetchTweets = async () => {
if(global.window) {
const res = await
fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
}
Server Error Error: Error serializing .tweets returned from
getServerSideProps in "/". Reason: undefined cannot be serialized
as JSON. Please use null or omit this value.
If someone can help me <3 thanks

FIXED :
.env.local
i writed
NEXT_PUBLIC_BASE_URL=https://localhost:3000/
change https:// by http:// and yarn run dev again
NEXT_PUBLIC_BASE_URL=http://localhost:3000/

Related

GET internal server error (500) with Next.js and React [duplicate]

This question already has answers here:
Internal API fetch with getServerSideProps? (Next.js)
(3 answers)
Closed 8 months ago.
I'm developing a website for a college class, followed a tutorial on YouTube since I have no real experience with this level of coding. The site "works" locally...when I execute it, at first the screen is just white, but if I refresh the page it comes up, and everything functions (it's a pizza website, the products and ordering and everything works locally). But, when I inspect while the screen is white, I see that I'm getting an internal server error:
I believe the issue is somewhere in my api/products/index file, but I'm not sure
Here is the code for that file:
import dbConnect from "../../../utilities/mongo"
import Product from "../../../models/Product"
export default async function handler(req, res) {
const {method, cookies} = req;
const token = cookies.token
dbConnect()
if(method === "GET"){
try {
const product = await Product.find();
res.status(200).json(product);
} catch (err) {
res.status(500).json(err)
}
}
if(method === "POST"){
if(!token || token !== process.env.TOKEN){
return res.status(401).json("Not Authorized")
}
try{
const product = await Product.create(req.body);
res.status(201).json(product)
}catch(err){
res.status(500).json(err);
}
}
}
Here is a link to my github with all code:
https://github.com/InvisibleH3R0/mellowyellowpizzaria
Any assistance on what is wrong would be highly appreciated!
EDIT:
Here are screenshots of my terminal:
Looking at your repo, I can see you are calling your API endpoint inside your getServerSideProps function in your index.js page. You should be writing your DB logic inside getServerSideProps directly since calling your endpoint in this function is considered inefficient and could give you some problems. You can read more about this here.
Try this:
export const getServerSideProps = async (ctx) => {
const myCookie = ctx.req?.cookies || "";
let admin = false;
if (myCookie.token === process.env.TOKEN) {
admin = true;
}
await dbConnect();
const res = await Product.find();
return {
props: {
pizzaList: JSON.parse(JSON.stringify(res)),
admin,
},
};
};

React & Sanity - Fetch Error: invalid JSON response body

I have been following a tutorial on youtube to build a twitter-clone website. However, when trying to fetch tweets from Sanity I am getting this error. I even git cloned the repo of the person that made the tutorial and I'm still getting the same error. This leads me to believe it is an issue with my VS code and not the code itself, if anyone has any suggestions that would be great thank you.
// fetchTweets.ts
export const fetchTweets = async () => {
const res = await fetch(`http://localhost:3001/api/getTweets`)
const data = await res?.json()
const tweets: Tweet[] = data.tweets
console.log('fetching', tweets)
return tweets
}
// index.tsx
export const getServerSideProps: GetServerSideProps = async (context) => {
const tweets: Tweet[] = await fetchTweets()
return {
props: {
tweets,
},
}
}
That error is typically caused by trying to render HTML as JSON—and particularly, when JSON is expected but instead an API returns an error page. Is your server definitely running on port 3001? Fetching from a non-existent server is likely consistent with this error.

why i'm not able to fetch data using axios call?

const [category, setCategory] = useState("general")
const news = await axios.get(`https://newsapi.org/v2/top-headlines?country=in&apiKey=64968be4903a4a979fe05c58a3355a73
&category=${category}`);
**As I am fetching API but its not fetching as is shows an empty array can anyone tell me where I am I going wrong **
You can not use the response of an async function directly in your React functional component. You have to use a state which holds your news. If you call setNews React automatically rerenders your component with the new news data.
export function News() {
const [category, setCategory] = useState("general");
const [news, setNews] = useState([]);
// fetch news everytime the category changes
useEffect(() => {
async function fetchNews() {
try {
const url = `https://newsapi.org/v2/top-headlines?country=in&apiKey=64968be4903a4a979fe05c58a3355a73&category=${category}`;
const response = await axios.get(url);
console.log(response);
setNews(response.data.articles);
} catch (errorWhileFetchingNews) {
console.log("error while fetching news", errorWhileFetchingNews);
}
}
fetchNews();
}, [category]);
// render the news
return (
<div>
{
news.map((article, i) => {
return <div key={i}>{article.title}</div>;
})
}
</div>
);
}
EDIT:
CAUTION: The CORS issues seem to appear only in my codesandbox example. If the example above runs on localhost:3000 in a normal React app (create-react-app) it works like it should. So you might ignore the following description.
Unfortunately the server newsapi.org doesn't send CORS headers. So you are not allowed to call this service directly via AJAX requests (axios, fetch, ...). You either find a way to enable CORS on this site (because you have an API key you may be able to administrate something?) or you find an other service that supports CORS or you have to send your request through a proxy. The proxy/backend then have to run on the same domain (host + port) like your frontend or the proxy must handle all the CORS header stuff. There are also questions on stackoverflow that have the same issue with newsapi.org but I am afraid that there is no easy solution/workaround for this.
I have setup a working example with jsonplaceholder.typicode.com (supports CORS) instead of newsapi.org.
See here: https://codesandbox.io/s/white-wildflower-su5vd?file=/src/News.js
Just in case the example is not reachable anymore, here is the code:
import { useState, useEffect } from "react";
import axios from "axios";
export function News(props) {
const [category, setCategory] = useState("general");
const [news, setNews] = useState([]);
// fetch news everytime the category changes
useEffect(() => {
async function fetchNews() {
try {
const url = "https://jsonplaceholder.typicode.com/comments";
const response = await axios.get(url);
console.log(response);
setNews(response.data);
} catch (errorWhileFetchingNews) {
console.log("error while fetching news", errorWhileFetchingNews);
}
}
fetchNews();
}, [category]);
// render the news
return (
<div>
{
news.map((article) => {
return <div key={article.id}>{article.name}</div>;
})
}
</div>
);
}

Next Js project getServerSideProps

I'm learning Next.js and run into a problem. I was following a tutorial on youtube to make a google clone with the next.js + tailwind. So the problem is when I add export async function getServerSideProps() I get an error invalid JSON response body. Reason: Unexpected token < in JSON at position 0
Seems I am doing everything exactly as the instructor but he doesn't get any error.
export async function getServerSideProps(context) {
const useDummyData = false;
const data = await fetch(
`https://developers.google.com/custom-search/v1?
key=${API_KEY}&cx=${CONTEXT_KEY}&q=${context.query.term}`
).then((response) => response.json());
return {
props: {
results: data,
},
};
}

Firebase Jest auth/network-request-failed' error

I'm trying to do Firebase testing Using Jest. This is my test case.
test('Test Firebase Connection', done => {
let history = [];
function callback(history) {
expect(history[0]).toBe('/dashboard');
done();
}
firebaseDAO.init('myEmail', 'mypassword', history);
setTimeout(callback, 4000,history);
});
export const init = (username, passwordPassed, history) => {
let historyData = history;
const email = username;
const password = passwordPassed;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);
promise.catch(e => console.log(e));
promise.then(() => {historyData.push('/dashboard');});
};
When I run the test with Idea-Webstorm-Jest Plugin it Works. (Test passes.)
But when I try with npm Test command. Firebase gives me following Error.
{code: 'auth/network-request-failed',
message: 'A network error (such as timeout, interrupted connection or unreachable host) has occurred.' }
So why it is fails when npm Test command runs? Anyone can help me? thanks in advance.
I had that problem too, i looked for google and i found that my input or button in html was in type:"submit" which made the page refresh, it's better to do type"button"

Resources