I have a cors issue in my development with vue3 & vite, so I create a proxy config in my vite.config.js
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { resolve } from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': resolve(__dirname, 'src'),
},
},
server: {
proxy: {
"/api": {
target: "https://###.com",
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, ""),
},
}
}
})
when I use in my app my method:
createPayment() {
const url = "/api/webhook/###";
let formData = new FormData();
formData.append("firstName", this.first_name);
formData.append("lastName", this.last_name);
formData.append("email", this.email);
formData.append("phone", this.phone);
formData.append("cardNumber", this.c_number);
formData.append("cardExpiration", this.c_EXP);
formData.append("cardCCV", this.c_CVC);
const request = new Request(url, {
method: "POST",
body: formData,
headers: {
accept: 'application/json',
contentType: "application/json;charset=UTF-8",
AccessControlAllowOrigin: '*'
},
});
fetch(request)
.then(result => console.log(result))
.catch(error => console.log('error', error));
},
The Post all ways send from localhost, I can't understand why?
I make the config for change '/api' to 'https://###.com' ?
My Log:
Response {type: 'basic', url: 'http://localhost:3000/api/webhook/####', redirected: false, status: 404, ok: false, …}
Related
I tried to configure a next js project with supabase
But the data I receive is not consistent
To do this I have configured the following 3 files :
.env.local
NEXT_PUBLIC_SUPABASE_URL= ********
NEXT_PUBLIC_SUPABASE_ANON_KEY= ********
supabase.js
import { createClient } from '#supabase/supabase-js'
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
)
export default supabase;
pages/api/posts.js
import supabase from '../../utils/supabase';
export default function handler(req, res) {
const posts = supabase.from("posts").select("*");
res.status(200).json(posts);
}
When I console log my posts variable, I have no data property.
It returned this,
PostgrestFilterBuilder {
fetch: [Function (anonymous)],
shouldThrowOnError: false,
allowEmpty: false,
url: URL {
href: '********/rest/v1/posts?select=*',
origin: '********',
protocol: 'https:',
username: '',
password: '',
host: '********',
hostname: '********',
port: '',
pathname: '/rest/v1/posts',
search: '?select=*',
searchParams: URLSearchParams { 'select' => '*' },
hash: ''
},
headers: {
'X-Client-Info': 'supabase-js/1.35.4',
apikey: '********',
Authorization: 'Bearer ********'
},
schema: 'public',
_subscription: null,
_realtime: RealtimeClient {
accessToken: null,
channels: [],
endPoint: 'wss://********/realtime/v1/websocket',
headers: { 'X-Client-Info': 'supabase-js/1.35.4' },
params: {
apikey: '********'
},
timeout: 10000,
transport: [Function: W3CWebSocket],
heartbeatIntervalMs: 30000,
longpollerTimeout: 20000,
heartbeatTimer: undefined,
pendingHeartbeatRef: null,
ref: 0,
logger: [Function: noop],
conn: null,
sendBuffer: [],
serializer: Serializer { HEADER_LENGTH: 1 },
stateChangeCallbacks: { open: [], close: [], error: [], message: [] },
reconnectAfterMs: [Function (anonymous)],
encode: [Function (anonymous)],
decode: [Function: bound decode],
reconnectTimer: Timer {
callback: [Function (anonymous)],
timerCalc: [Function (anonymous)],
timer: undefined,
tries: 0
}
},
_headers: {
'X-Client-Info': 'supabase-js/1.35.4',
apikey: '********',
Authorization: 'Bearer ********'
},
_schema: 'public',
_table: 'posts',
method: 'GET',
cs: [Function: contains],
cd: [Function: containedBy],
sl: [Function: rangeLt],
sr: [Function: rangeGt],
nxl: [Function: rangeGte],
nxr: [Function: rangeLte],
adj: [Function: rangeAdjacent],
ov: [Function: overlaps]
}
Also when I look at the dashboard of my supabase database I see that no query is receive
It seems that this query is not sent to the supabase API but I have no idea why ?
You need to await the Promise: https://supabase.com/docs/reference/javascript/select
import supabase from '../../utils/supabase';
export default async function handler(req, res) {
const posts = await supabase.from("posts").select("*");
res.status(200).json(posts);
}
I want to enable CORS for all sources and destinations from my app.
I am following this https://vercel.com/guides/how-to-enable-cors as my deployment of the Nextjs app is on Vercel.
Below is my next.config.js file.
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false,
swcMinify: true,
eslint: {
ignoreDuringBuilds: true,
},
async headers() {
return [
{
source: '/',
headers: [
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Allow-Origin', value: '*' },
{
key: 'Access-Control-Allow-Methods',
value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT',
},
{
key: 'Access-Control-Allow-Headers',
value:
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
},
],
},
]
},
}
module.exports = nextConfig
The aim is to allow Access-Control-Allow-Origin: "*" for all the API calls from the app.
I am using RTK-Query, and Redux-toolkit for this app, and I created an api-slice with createApi, as per the docs.
When I run a request to the backend, I get a "FETCH_ERROR"; however, when I run the same request using Axios, I get the data correctly from the backend, which leads me to believe I have an error in my code. I am just not sure where exactly it is.
Here is the error:
Object {
"api": Object {
"config": Object {
"focused": true,
"keepUnusedDataFor": 60,
"middlewareRegistered": true,
"online": true,
"reducerPath": "api",
"refetchOnFocus": false,
"refetchOnMountOrArgChange": false,
"refetchOnReconnect": false,
},
"mutations": Object {},
"provided": Object {},
"queries": Object {
"test(undefined)": Object {
"endpointName": "test",
"error": Object {
"error": "TypeError: Network request failed",
"status": "FETCH_ERROR",
},
"requestId": "BWOuLpOxoDKTzlUYFLW4x",
"startedTimeStamp": 1643667104869,
"status": "rejected",
},
},
"subscriptions": Object {
"test(undefined)": Object {
"QJSCV641RznGWyudGWuMb": Object {
"pollingInterval": 0,
"refetchOnFocus": undefined,
"refetchOnReconnect": undefined,
},
},
},
},
"test": Object {
"data": Array [],
},
}
Here is the test slice:
import { createSlice } from "#reduxjs/toolkit";
const testSlice = createSlice({
name: "test",
initialState: {
data: [],
},
reducers: {
getData: (state) => {
state;
},
},
});
export const { getData } = testSlice.actions;
export default testSlice.reducer;
Here is the apiSlice:
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
export const apiSice = createApi({
reducerPath: "test",
baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_backend_url }),
endpoints: (builder) => ({
test: builder.query({
query: () => "/test",
}),
}),
});
export const { useTestQuery } = apiSice;
I solved it by changing the backend URL to my current ipv4 (for expo development, otherwise just your whatever your backend URL is) address in my .env file, then deleting cache, and restarting my app. In my case I was using expo so, expo r -c, and it worked.
I want to redirect all traffic to my pricing page via a subdomain to my homepage. I can't figure out how to add wildcards in the has value.
This syntax does not work:
// next.config.js
module.exports = {
target: 'serverless',
async redirects() {
return [
{
source: '/pricing',
has: [
{
type: 'host',
value: '*.*.*',
},
],
permanent: false,
destination: 'https://example.com/'
}
]
},
}
Any ideas?
Vercel support helped me find the solution. I needed to update my regex in the value.
// next.config.js
module.exports = {
target: 'serverless',
async redirects() {
return [
{
source: '/pricing',
has: [
{
type: 'host',
value: '.*\\..*\\..*'
},
],
permanent: false,
destination: 'https://example.com/'
}
]
},
}
If you want to redirect the subdomain, you would add the redirect on that project. If you want the contents of the subdomain (e.g. pricing.example.com) to show up on a different project at /pricing, you would use a rewrite.
module.exports = {
async rewrites() {
return [
{
source: '/pricing',
destination: 'https://pricing.example.com'
},
]
},
}
As explained in the NextJs documentation: https://nextjs.org/docs/api-reference/next.config.js/headers , it is possible to configure the HTTP headers of a page using the code below, however my code is not working.
Next Example:
module.exports = {
async headers() {
return [
{
source: '/about',
headers: [
{
key: 'x-custom-header',
value: 'my custom header value',
},
{
key: 'x-another-custom-header',
value: 'my other custom header value',
},
],
},
]
},
}
My Code:
module.exports = {
async headers() {
return [
{
source: '/about',
headers: [
{
key: 'cache-control',
value: 'max-age=31536000',
},
],
},
]
},
}