How to specify HTTP response code in next.js - reactjs

I have a Next.js v12 application written in TypeScript.
I have a _error.tsx page providing custom UI experience for various errors, including 410, 404 and other ones. The issue is, whatever API error triggers the appearance of this page on the server-side, the client browser GETs this page from server with the HTTP status code of 500.
How could I customize that status code, so that for example the page for 410 actually has the HTTP status code of 410?

Well, I managed to find the solution on my own.
It's a little bit counter-intuitive, but to get the desired behavior you should just directly set the value of statusCode of the res object coming into getInitialProps of the said _error.tsx page.
Along these lines:
ErrorPage.getInitialProps = ({ res, err }: NextPageContext) => {
const statusCode =
(err as AxiosError)?.response?.status ?? res?.statusCode ?? err?.statusCode ?? undefined;
if (res && statusCode) {
res.statusCode = statusCode;
}
const text = String(res?.statusMessage || err?.message || err);
return { statusCode, text };
};

Related

Error handling response: Error: Blocked a frame (...) from accessing a cross-origin frame

I am fetching a calendly embed link dynamically into a next.js13 app, and technically, it is working. However, sometimes the embed doesn't fetch, resulting in a screen that looks like this:
ONLY upon refresh, the embed populates, and the console shows the error:
After doing some research, it seems as though this could be a CORS issue, though I am not sure. The way the embeds are pulled in is from supabase, through a fetch function and then passed to the static page like so:
export default async function HostPage({
params: { username },
}: {
params: { username: string };
}) {
const { data: profile } = await supabase
.from("profiles")
.select()
.match({ username })
.single();
const [host] = await Promise.all([profile]);
return (<div
data-url={profile.calendar_embed}
></div>)
To recap:
Sometimes, the embed gets fetched and displays right away. Errors are shown in the console
Some other times, the page remains empty, no errors in the console.
Upon refresh, the embed appears, with errors in the console.
Does anybody have an idea and can point me in the right direction?
Thanks in advance.

Getting 500 | Internal Server Error when using getServerSideProps only on host (not local)

I know it's an old question but I couldn't resolve this issue. I have a dynamic page using ssr (getServerSidePros). It is working perfectly on my localhost (both of development and production mode), but when I publish it ,I see 500|Internal Server Error. In my console window I see this:
main-50de763069eba4b2.js:1 A client-side exception has occurred, see here for more info: https://nextjs.org/docs/messages/client-side-exception-occurred and I don't get any details.
This is my code
export async function getServerSideProps(context:any) {
var id:number=context.params.id
console.log(context.params.id)
var data:any={}
const getData=async()=>{
const response:any= await axios.get(`http://localhost:99/api/v1/Blog/${id}`)
data=response.data
return data
}
data=await getData();
data=JSON.parse(JSON.stringify(data))
return {
props: {data}, // will be passed to the page component as props
}
}
Some solutions I've tried:
1-adding "main":"index.js"
2-adding axios.defaults.httpsAgent=new https.Agent({rejectUnauthorized:false,})
3-using .json() instead of JSON.stringify()

react-jsonp giving a CORB error in a React App

Edit
based on suggestions tried doing it with fetch, now I am getting this
I am trying to get data from gnews.io/api in a simple react app.I am learning React and the solution might have been to easy but I am stuck here and cant figure out what is wrong and I keep getting this error
fetch-jsonp.js:88 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://gnews.io/api/v4/top-headlines?country=us&token=myapi with MIME type application/json.
funny thing is that if I copy this url https://gnews.io/api/v4/top-headlines?country=us&token=MYAPI&callback=jsonp_1642257010280_37644
and paste it in the browser I am getting the desired response.
Would really appreciate any sort of help
this is the useEffect function that is making this api call
React.useEffect(()=> {
async function getNewsdata(country){
try {
let url = `https://www.gnews.io/api/v4/top-headlines?country=pk&token=${API2}`
let response = await fetchJsonp(url)
let result = await response.json()
console.log("News Data:", result)
} catch (error) {
console.log("error loading news data: ", error)
}
}
getNewsdata(props.country.trim())
},[])
Resorting to JSONP is frowned upon nowadays; there are safer alternatives, such as CORS, for cross-origin communication. As the response's content type is application/json, using JSONP will not work anyway because it causes Chrome's CORB feature to kick in.
Why not try to solve whatever CORS issue you seem to be having? I'd be very surprised if the API you're using weren't configured for CORS... A casual inspection of their documentation reveals that you're using the wrong domain, www.gnews.io, instead of gnews.io. The former redirects to the latter, but is not configured for CORS, which explains your CORS troubles.
Once you use the right domain (gnews.io), all your CORS troubles go away. And because there's no longer any need to reach for dirty tricks like JSONP, you can use good old reliable fetch rather than some third-party tool.
React.useEffect(()=> {
async function getNewsdata(country){
try {
let url = `https://gnews.io/api/v4/top-headlines?country=pk&token=${API2}` // gnews.io, not www.gnews.io
let response = await fetch(url) // fetch, not fetchJsonp
let result = await response.json()
console.log("News Data:", result)
} catch (error) {
console.log("error loading news data: ", error)
}
}
getNewsdata(props.country.trim())
},[])

It was set headers and axios but Why happen cros error?

Premise / What you want to achieve
React x Redux (port: 3000)
Go (port: 8080)
I am making a SPA.
I run into a CROS error when hitting the Go API.
I've encountered this problem many times, and every time I think it's solved, I hit a new API.
I should have made the basic settings, but I'm in trouble because I don't know what caused it.
We would appreciate it if you could help us.
Problem / Error message
Access to XMLHttpRequest at'http://localhost:8080/login' from origin'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No'Access-Control -Allow-Origin'header is present on the requested resource.
I encountered this when I hit the login API (post).
However, when I encountered this problem several times, I set cros on the header of api and axios side, and
Another get API avoided the error.
Also, when you hit api with postman, it becomes header
We have also confirmed that the header set in Go such as Allow-Origin is given without any problem.
Applicable source code
Header settings in Go
w.Header (). Set ("Content-Type", "application /json")
w.Header (). Set ("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header (). Set ("Access-Control-Allow-Credentials", "true")
react axios settings
axios.defaults.baseURL ='http://localhost:8080';
axios.defaults.headers.post ['Content-Type'] ='application/json';
Posting code with an error
export const signIn = (email, password) => {
return async (dispatch) => {
try {
const response = await axios.post ('/login', {
email: email,
password: password,
});
const data = response.data;
dispatch (
signInAction ({
isSignedIn: true,
})
);
} catch (error) {
console.log (error);
}
};
};
Code hitting a successful getapi
useEffect (() => {
async function fetchTickers () {
try {
const response = await axios.get (`/ticker?Symbol=^skew`);
const data = response.data;
setChartAry ([... chartAry, [... data.daily]]);
} catch (error) {
console.log (error);
setChartAry ([]);
}
}
fetchTickers ();
}, []);
What I tried
I tried all the solutions that hit with stackoverflow etc. Also, considering the possibility of a problem with the browser itself, we also cleared the cache.
Is it the difference between axios by get and post? And how should I debug it?
I had this problem some time ago but I used Express for the backend, who knows this can solve your problem too.
try adding this to the axios settings axios.defaults.withCredentials = true;
You also need to allow the OPTIONS method for preflight requests
this article might help you solve the CORS problem on the backend: https://flaviocopes.com/golang-enable-cors/
The method was validated in gorilla / mux.
- r.HandleFunc("/login", app.loginHandler).Methods("POST")
+ r.HandleFunc("/login", app.loginHandler).Methods("POST", "OPTIONS")
We also had to deal with preflight.
if r.Method == "OPTIONS" {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.WriteHeader(http.StatusOK)
return
}

How to hide console status error message while fetching in React js?

In my React app, I'm using fetch() to get data from my API, _callAPI() function gets domain parameter and call API if a website of the domain exists in my DB. If it exists, it returns the website's object, otherwise it returns 500. So, I can't figure out if the website exists until I use fetch(). The problem is that every time fetch() doesn't find anything, it throws the following:
container.jsx:25 GET
http://localhost:3000/boutiques/detail/?q=testdomain.com
500 (Internal Server Error)
When it doesn't doesn't find a lot of websites, the console log is packed with that error message. Is there a way to ignore that sort of message while fetching?
fetch()
_callApi = () => {
const { domain } = this.props;
return fetch(`/boutiques/detail/?q=${domain}`)
.then(response => {
if (response.status === 500) {
return 500;
}
return response.json();
})
.then(json => json)
.catch(err => console.log(err));
};
If you want to mute the browser error:
Unfortunately, this cannot be done, as this type of message in the
console is printed by chrome itself. Repressing this type of message
has been debated for years, but the consensus seems to be that this
message is desirable
Credits.
If you want to mute the Unhandled error in the console:
You can always mute the error on front-end, as follows:
.catch(err => { const mute = err })
But it would be better to notify somehow the user about the error and not doing such workarounds.
Also it would better your server to return an error message in the response and on the front-end side you will proceed it.
Looking into your case, it may be better the server to response with status code 400. Here are the HTTP error codes and their purpose:
4xx (Client Error): The request contains bad syntax or cannot be
fulfilled
5xx (Server Error): The server failed to fulfill an
apparently valid request

Resources