I have the following code, I am using React:
// post-post
const queryDatabase = (obj, endpoint) => {
console.log(obj);
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(obj)
};
console.log(endpoint);
fetch(endpoint, requestOptions)
.then(data => {return Promise.resolve(data)}
);
}
export {queryDatabase};
For some reason console.log(endpoint) prints the endpoint that I am passing in, e.g. "/users", "/profile" etc. However, fetch is trying to send to http://localhost:3000/users so when I try to manually pass in an endpoint I get an error about trying to post to http://localhost/http://localhost/users.
Where is fetch getting this default http://localhost:3000 value?
It's only doing this for POST requests.
The only environment variables are the following:
REACT_APP_AUTH0_REDIRECT_URI=http://localhost:3000
REACT_API_SERVER_URL=http://api.localhost
PORT=3000
I also have some other environment variables for Auth0, is Auth0 doing this? I've removed these variables for testing and still nothing.
The answer is to use the Request object and pass that through to fetch:
const requestOptions = new Request(serverUrl + endpoint, {
method: 'POST',
body: JSON.stringify(obj),
headers: new Headers({
'Content-Type': 'application/json'
})
});
Why bother... use axios or something else, fetch sucks.
EDIT:
Apparently not a problem with fetch. Whatever the case this is the fix.
Related
I'm trying to display the data comes back from a server, I can see the data coming back from the server I'm hitting when I look at network tab in Chrome's developer window.
How can I get access to it in my code below?
The handleClick method is called when a button is clicked.
Thanks!
let data;
async function handleClick() {
const url = "http://127.0.0.1:8000/parse"
data = await fetch(url, {
mode: 'no-cors',
method: "POST",
headers: { 'Content-type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
locale: "en_GB",
text: "Test Message"
})
})
.then(x => x.text())
console.log(data)
}
// Capture in the promise return section
.then(x => {
// Catch the data through the propertiesName.
// Here properties means your post request's variable name which you are given.
console.log(x.propertiesName);
});
I am using getStaticProps and getStaticPaths, I used fetch API to call an API endpoint (which is Wordpress headless CMS in my case) and set the paths for dynamic routing. When I run npm dev it works fine, the data is fetched correctly. But at build time it gives error that:
FetchError: invalid json response body at https://abr.af/wp/wp-json/wp/v2/advisors reason: Unexpected token < in JSON at position 0
My code in pages/advisor/[advisor].js
export const getStaticPaths = async () => {
const advisors = await getAdvisors()
const paths = advisors.map((each) => {
return {
params: { advisor: each.slug },
}
})
return {
paths,
fallback: false,
}
}
export const getStaticProps = async ({ params }) => {
const query = params.advisor
const advisors = await getAdvisors()
const advisor = advisors.find((advisor) => advisor.slug === query)
return {
props: {
advisor,
},
}
}
my fetch function in component/FetchData.js
export async function getAdvisors() {
const res = await fetch('https://abr.af/wp/wp-json/wp/v2/advisors', {
method: 'GET',
headers: {
// update with your user-agent
'User-Agent': '*',
Accept: 'application/json; charset=UTF-8',
},
})
const advisors = await res.json()
return advisors
}
export async function getExpertise() {
const res = await fetch('https://abr.af/wp/wp-json/wp/v2/expertise', {
method: 'GET',
headers: {
// update with your user-agent
'User-Agent': '*',
Accept: 'application/json; charset=UTF-8',
},
})
const expertise = await res.json()
return expertise
}
I googled this issue and find that I should add User-Agent header to my request but this not solve my problem.
I am new to Next.js, I don't know what is the reason any help would be appreciated.
I had the same error, and had to switch to getServerSideProps. For my case, the api I was using was a next api that was not readily available during build time (db connection + fetching).
I had to go back to NextJS documentation, to understand when you should use getStaticProps.
And this is what is stated:
The data required to render the page is available at build time ahead
of a user’s request.
The data comes from a headless CMS.
The data can
be publicly cached (not user-specific).
The page must be pre-rendered
(for SEO) and be very fast — getStaticProps generates HTML and JSON
files, both of which can be cached by a CDN for performance.
please, help me check this post request.
I've been looking at it since yesterday, I don't know what is wrong with it
maybe I need another developer's pairs of eyes.
thanks in advance
buttons.addEventListener('click', ()=>{
fetch("https://jsonplaceholder.typicode.com/comments", config)
.then(res=>{
res.json();
}).then(datae=>{
console.log(datae);
})
});
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newName)
}
buttons.addEventListener('click', () => {
fetch('https://jsonplaceholder.typicode.com/comments', config)
.then((res) => {
return res.json()
})
.then((datae) => {
console.log(datae)
})
})
you just need to return res.json()
this should work, but remember that the function you pass to the .then function has access to the returned value from the previous .then.
fetch returns a promise that resolves into an object with the .json function
so in the first .then it will get that object and you need to return res.json() which returns a promise that will be resolved to the JSON data
so in the next .then you can use that data
I hope I was clear
note:
.then function returns a promise ( always )
also maybe you have an error in the config variable, what you pass to the JSON.stringify function should be a valid javascript object
const config = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'rowadz' }),
}
I'm trying to make http request in react native app and it throws me an error
Uncaught Error: unsupported BodyInit type
at Response.Body._initBody (index.bundle?platform=android&dev=true&minify=false:13594)
at new Response (index.bundle?platform=android&dev=true&minify=false:13765)
at XMLHttpRequest.xhr.onload (index.bundle?platform=android&dev=true&minify=false:13820)
in index.js of the app I added this line
GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest
fetch request
const headers = {};
headers['Accept'] = 'application/json';
headers['Content-Type'] = 'application/json';
let response = await fetch('https://www.saramashkim.co.il/api/get_all_product', {
method: 'GET',
headers: headers,
body: null,
})
when I check this url in POSTMAN it works fine and I get all data..
Try the code below:
var headers = {'Accept': 'application/json', 'Content-Type': 'application/json'};
fetch('https://www.saramashkim.co.il/api/get_all_product', {
method: 'GET',
headers: headers,
}).then((response) => response.json())
.then((responseJson) => {
console.log('response', responseJson);
})
.catch((error) =>{
console.error(error);
});
You can see the response is logged to console. (I've updated my answer)
repl: https://repl.it/#tejashwikalptar/samplefetchtest
Screenshot:
I am attempting to fetch some data from a GraphQL endpoint, however I keep getting the error "Must provide query string". I am sure I am providing the query string, where does this error come from?
The endpoint is: https://antserver-blocjgjbpw.now.sh/graphql
const query = `{
ants {
name
color
length
weight
}
}`
document.getElementById("basicFetchButton").addEventListener("click", () => {
fetch("https://antserver-blocjgjbpw.now.sh/graphql", {
method: 'POST',
'Content-Type': 'application/graphql',
body: JSON.stringify({query})
})
.then(res => res.json())
.then(data => console.log(data))
})
In this case, you want to use Content-Type: 'application/json'. application/graphql requires the entire body of the request to be the query, but I don't recommend that approach since it's impossible to send query variables.
Here's a full code sample:
fetch('https://antserver-blocjgjbpw.now.sh/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query }),
})
.then(res => res.json())
.then(res => console.log(res.data));
For more examples, check out my article 4 simple ways to call a GraphQL API