When I try to fetch data from payload cms, I tried to use fetch() but it failed because it did need to set mode: 'no-cors'
when I set headers: {'content-type' : 'application/json'} but it didn't work and type is text/plain
const result = await fetch(PUBLIC_PAYLOAD_SERVER_URL, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'content-type': 'application/json'
}),
body: GetSiteBannerQuery()
});
In payload do you have the cors configured?
Is payload on a server or running locally?
payload is running locally
@noheadphones it doesn't work.
this is server config:
you shouldnt need to fetch with
no-cors
mode
import { buildConfig } from 'payload/config';
import path from 'path';
import SiteBanner from './globals/SiteBanner';
import Users from './collections/Users';
export default buildConfig({
serverURL: 'http://localhost:3000',
admin: {
user: Users.slug,
},
collections: [
Users,
],
globals: [
SiteBanner
],
typescript: {
outputFile: path.resolve(__dirname, 'payload-types.ts'),
},
graphQL: {
schemaOutputFile: path.resolve(__dirname, 'generated-schema.graphql'),
},
plugins: []
});
does
GetSiteBannerQuery
return a graphql query?
export const GetSiteBannerQuery = () => {
return JSON.stringify(
{
query: `query SiteBannerQuery {
SiteBanner {
backgroundColor
textColor
textContent
isActive
}
}`
}
);
};
const result = await fetch(PUBLIC_PAYLOAD_SERVER_URL, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'content-type': 'application/json'
}),
body: GetSiteBannerQuery()
});
for development/testing only I'd set
cors
and
csrf
to
['*']
it doesn't work out.
const getSiteBanner = async () => {
const result = await fetch("http://localhost:3000/api/graphql", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: GetSiteBannerQuery()
});
const resultSiteBanner = await result.json();
console.log('result site banner: ', resultSiteBanner);
if (resultSiteBanner?.data?.SiteBanner) {
siteBanner = resultSiteBanner?.data?.SiteBanner;
}
};
import { buildConfig } from 'payload/config';
import path from 'path';
import SiteBanner from './globals/SiteBanner';
import Users from './collections/Users';
export default buildConfig({
serverURL: 'http://localhost:3000',
cors: ['*'],
csrf: ['*'],
admin: {
user: Users.slug,
},
collections: [
Users,
],
globals: [
SiteBanner
],
typescript: {
outputFile: path.resolve(__dirname, 'payload-types.ts'),
},
graphQL: {
schemaOutputFile: path.resolve(__dirname, 'generated-schema.graphql'),
},
plugins: []
});
@noheadphones @dribbens @jmikrut I hope you would help me give some direction to fix this issue.
im comparing it to my code, I can't see anything clearly obvious
do you think you can package this in a reproducible repo?
Hi @noheadphones
I fixed issue.
Thank you. 🙂
Great! What was the problem?
I had to set No-Cors.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.