W
Wasp-lang4mo ago
ArDev

CORS Issues

is it okay to modify the main.wasp file?
84 Replies
kapa.ai
kapa.ai4mo ago
Hi @ArDev. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Yes, it is okay to modify the main.wasp file. This file is your app's definition file and it defines the app's central components. It is a list of declarations, each of which defines a part of your app. You can modify it to configure your app, define routes, pages, and more. However, it's important to note that currently, Wasp doesn't support dynamically changing the main.wasp file or splitting it into multiple .wasp files. These features are still in the works. However, you should avoid modifying any of the .wasp folder files as your changes will get overwritten the next time you start wasp start. If you need to customize the build process, you can provide your own custom Dockerfile in the project root (the same folder where main.wasp lives). Wasp will use it when building your server. Sources: - main.wasp (https://wasp-lang.dev/docs/tutorial/project-structure#mainwasp) - Discord support thread: Setting Environment-specific Values in main.wasp File > Answers (https://discord.com/channels/686873244791210014/1209467473389297684) - Discord support thread: Modular .wasp files? > Original post (https://discord.com/channels/686873244791210014/1184362101494534165) - Discord support thread: database url > Answers (https://discord.com/channels/686873244791210014/1205728717993672705) - Discord support thread: Issue with deploying my wasp app to fly.io > Answers Part 2 (https://discord.com/channels/686873244791210014/1223671727943319584) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
martinsos
martinsos4mo ago
Yup, you should be modifying it! Check our tutorial for basics of Wasp https://wasp-lang.dev/docs/tutorial/create
1. Creating a New Project | Wasp
You'll need to have the latest version of Wasp installed locally to follow this tutorial. If you haven't installed it yet, check out the QuickStart guide!
ArDev
ArDevOP4mo ago
import { search } from 'wasp/client/operations'; main.wasp - action search { fn: import {search }"@src/server/main/actions.js", entities: [User] }# is this a correct way to import? @kapa.ai
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
import { search } from 'wasp/client/operations'; main.wasp - action search { fn: import {search }"@src/server/main/actions.js", entities: [User] }# is this a correct way to import? @kapa.ai
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The import statement you've written in your main.wasp file seems to be incorrect. In Wasp, you define actions in the main.wasp file and then provide the implementation in a separate JavaScript file. Here is the correct way to define an action in main.wasp:
action search {
fn: import { search } from "@ext/server/actions.js"
entities: [User]
}
action search {
fn: import { search } from "@ext/server/actions.js"
entities: [User]
}
In the above code, search is the name of the function that implements the action, which is located in the actions.js file in the server directory of the ext folder. Then, in your actions.js file, you would define the search function like this:
export async function search({ args, context }) {
// Your implementation here
}
export async function search({ args, context }) {
// Your implementation here
}
Please note that the context argument contains useful information such as the authenticated user, Prisma client, and more. Sources: - Wasp Docs - Actions (https://wasp-lang.dev/docs/language/basic-elements#actions) - Github Issue - Fix docs on calling queries and actions on the server (https://github.com/wasp-lang/wasp/issues/1909) - Discord support thread - import actions into main.wasp (https://discord.com/channels/686873244791210014/1216119302244270181) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai how can i make it so i dont have to restart every time i make updates to my codebase? so i dont have to do wasp start all the time?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Wasp has a built-in hot reloading feature. When you run wasp start, it launches the Wasp app in development mode and watches for any changes to .wasp or files in src/ to automatically reflect in the browser. This means you don't have to restart the server every time you make changes to your codebase. However, there have been some reports in the community about issues with hot reloading, particularly with UI file changes causing full app reloads. The Wasp team is aware of this and is actively working on a fix. If you're experiencing issues with hot reloading, you might want to follow the progress on this issue on the Wasp GitHub page: https://github.com/wasp-lang/wasp/issues/1844 Sources: - Wasp CLI Reference (https://wasp-lang.dev/docs/general/cli#project-commands) - Discord support thread: Hot Reloading? (https://discord.com/channels/686873244791210014/1213985542480597022) - Discord support thread: Possibility to disable wasp reload on UI file changes? (https://discord.com/channels/686873244791210014/1223304305206099969) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
IamIconLiving
IamIconLiving4mo ago
However, there have been some reports in the community about issues with hot reloading, particularly with UI file changes causing full app reloads. The Wasp team is aware of this and is actively working on a fix.
is this still the case though? this was fixed if my memory doesn't fail me kapa indexes discord threads? 😮
miho
miho4mo ago
I believe the hot reloading issues are related strictly to WSL2 and having the project on Windows filesystem vs. the Linux filesystem. @kapa.ai am I right?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, you are correct. There is a known issue with WSL2 where file changes are not detected when your project is located on the Windows filesystem. This affects the hot reloading feature of Wasp (and other frameworks as well). The recommended workaround for this issue is to move your project into the Linux filesystem root directory when using WSL2. This will enable Wasp to detect changes in your project and trigger hot reloads. You will also likely notice an increase in performance compared to the Windows filesystem root directory. Here is a useful link for more information on this issue: https://github.com/microsoft/WSL/issues/4739 And here is a guide on how to do Wasp development on WSL: https://wasp-lang.dev/blog/2023/11/21/guide-windows-development-wasp-wsl Sources: - Github Issue (closed): File changes not detected by wasp start in WSL2 when using the Windows filesystem (https://github.com/wasp-lang/wasp/issues/603) - Discord support thread: Hot Reloading? (https://discord.com/channels/686873244791210014/1213985542480597022) - Docs > Quick Start > More details > Installation Part 2 (https://wasp-lang.dev/docs/quick-start#installation-1) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @miho, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
oh i see @kapa.ai can i move my project into linux file system with just copy/paste?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, you can move your project into the Linux filesystem by copying and pasting it. However, you need to ensure that you're doing this from within the WSL2 environment. Here's a general guide on how you can do it: 1. Open your WSL2 terminal. 2. Navigate to the directory where your project is currently located. For example, if your project is on your Windows desktop, you can access it in WSL2 with the command cd /mnt/c/Users/YourUserName/Desktop. 3. Copy your project directory to your desired location in the Linux filesystem. For example, to copy it to your home directory, you can use the command cp -r YourProjectName ~/. Please replace YourUserName and YourProjectName with your actual Windows username and your project's name. Remember, after moving the project, you should use a code editor running in the WSL environment to make changes to your project files. If you're using VSCode, you can do this by installing the Remote - WSL (https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl) extension. Sources: - Github Issue (closed): File changes not detected by wasp start in WSL2 when using the Windows filesystem (https://github.com/wasp-lang/wasp/issues/603) - Discord support thread: Hot Reloading? (https://discord.com/channels/686873244791210014/1213985542480597022) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai how do to api calls?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- In Wasp, you can make API calls using the api declaration. Here's a step-by-step guide on how to do it: 1. Declare the API in Wasp: You can do this in your main.wasp file using the api declaration. For example:
api fooBar {
fn: import { fooBar } from "@src/apis",
httpRoute: (GET, "/foo/bar")
}
api fooBar {
fn: import { fooBar } from "@src/apis",
httpRoute: (GET, "/foo/bar")
}
2. Define the API's NodeJS implementation: This should be a NodeJS function that takes three arguments: req (Express Request object), res (Express Response object), and context (an additional context object injected into the API by Wasp). For example:
export const fooBar = (req, res, context) => {
res.set("Access-Control-Allow-Origin", "*");
res.json({ msg: `Hello, ${context.user ? "registered user" : "stranger"}!` });
};
export const fooBar = (req, res, context) => {
res.set("Access-Control-Allow-Origin", "*");
res.json({ msg: `Hello, ${context.user ? "registered user" : "stranger"}!` });
};
3. Use the API from the client: You can use the API from your client by importing the Axios wrapper from wasp/client/api and invoking a call. For example:
import { api } from "wasp/client/api";

async function fetchCustomRoute() {
const res = await api.get("/foo/bar");
console.log(res.data);
}
import { api } from "wasp/client/api";

async function fetchCustomRoute() {
const res = await api.get("/foo/bar");
console.log(res.data);
}
Remember to ensure that CORS (Cross-Origin Resource Sharing) is enabled to use these APIs on the client side. You can do this by defining custom middleware for your APIs in the Wasp file. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Wasp Docs - Using the API from the Client (https://wasp-lang.dev/docs/advanced/apis#using-the-api-from-the-client) - Wasp Docs - Defining the API's NodeJS Implementation (https://wasp-lang.dev/docs/advanced/apis#defining-the-apis-nodejs-implementation) - Wasp Docs - Making Sure CORS Works (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
An error occurred while searching comments: Network Error Debug Information: Initiating search... Error details: { "message": "Network Error", "name": "AxiosError", "stack": "AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:3000/node_modules/.vite/deps/axios.js?v=5fa66a6e:1439:14)\n at Axios.request (http://localhost:3000/node_modules/.vite/deps/axios.js?v=5fa66a6e:1769:41)\n at async handleSearch (mydirx?t=1724069808875:35:24)", "config": { "transitional": { "silentJSONParsing": true, "forcedJSONParsing": true, "clarifyTimeoutError": false }, "adapter": [ "xhr", "http" ], "transformRequest": [ null ], "transformResponse": [ null ], "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "maxBodyLength": -1, "env": {}, "headers": { "Accept": "application/json, text/plain, /", "Content-Type": "application/json" }, "baseURL": "http://localhost:3001/", "method": "post", "url": "/api/search-t", "data": "{"apiKey":"AIzaSyAUDIBHzaVaxMIa1fa5-O39UzGYVGwLwU0","channelInput":"mreflow","query":"h"}" }, "code": "ERR_NETWORK", "status": null } Error occurred: Network Error Stack trace: AxiosError: Network Error at XMLHttpRequest.handleError (http://localhost:3000/node_modules/.vite/deps/axios.js?v=5fa66a6e:1439:14) at Axios.request (http://localhost:3000/node_modules/.vite/deps/axios.js?v=5fa66a6e:1769:41) at async handleSearch (http://localhost:3000/@fs/mydir/search.tsx?t=1724069808875:35:24) @kapa.ai
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message "Network Error" typically indicates that the client is unable to establish a network connection to the server. In this case, it seems like your client-side code is trying to make a request to <http://localhost:3001/api/search-t> but is unable to reach the server. Here are a few things you can check: 1. Server is running: Make sure your server is running and listening on the correct port (3001 in this case). 2. Correct URL: Ensure that the URL you're trying to reach is correct. In this case, it's <http://localhost:3001/api/search-t.> If your server is running on a different port or if the API endpoint is different, you'll need to update the URL accordingly. 3. Network issues: If your server is running and the URL is correct, there might be network issues preventing the client from reaching the server. This could be due to firewall settings, network configuration issues, etc. 4. CORS: If your client and server are running on different domains (which is the case here since they're on different ports), you'll need to ensure that CORS (Cross-Origin Resource Sharing) is properly configured on the server. This allows the server to accept requests from different domains. If you're using Wasp, you can define custom middleware for your APIs in the Wasp file to enable CORS. Here's an example:
main.js:
import cors from 'cors'

export const middleware = [
{ name: 'cors', fn: cors() }
]
main.js:
import cors from 'cors'

export const middleware = [
{ name: 'cors', fn: cors() }
]
This will apply the cors middleware to all your APIs, allowing them to accept requests from different domains. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Wasp Docs - Making Sure CORS Works (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) - Discord support thread: AxiosError (https://discord.com/channels/686873244791210014/1222010179537866902) - Discord support thread: ngrok... (https://discord.com/channels/686873244791210014/1218081390176763914) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai AxiosError: Request failed with status code 400
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message "AxiosError: Request failed with status code 400" typically indicates a "Bad Request." This means that the server was unable to understand the request due to invalid syntax. Here are a few things you can check: 1. Request Method: Ensure that you're using the correct HTTP method (GET, POST, PUT, DELETE, etc.) for your request. 2. Request URL: Make sure the URL you're trying to reach is correct and that the server has a route matching this URL. 3. Request Headers: Check if the server expects any specific headers and if they are included in your request. 4. Request Body: If your request includes a body (like in a POST or PUT request), ensure that it's correctly formatted and matches what the server expects. This could be a JSON object, form data, etc. 5. Query Parameters: If your request includes query parameters, make sure they are correctly formatted and expected by the server. If you're using Wasp and have defined your API endpoints using the api declaration, ensure that your client-side code is correctly calling these APIs. You can use the api object from wasp/client/api to make requests to your server-side APIs. If none of the above solutions work, you might want to look at the server logs or use a tool like Postman to manually send requests to your server and see the response. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Discord support thread: AxiosError (https://discord.com/channels/686873244791210014/1222010179537866902) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai how to properly communicate with apis in wasp? this is how im importing import { api } from 'wasp/client/api'; and then use it through api.post(mycommand)
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, you're on the right track. In Wasp, you can use the api object from wasp/client/api to make requests to your server-side APIs. Here's a step-by-step guide on how to do it: 1. Import the api object: At the top of your file, you should import the api object from wasp/client/api like you've done:
import { api } from 'wasp/client/api';
import { api } from 'wasp/client/api';
2. Use the api object to make requests: You can use the api object to make GET, POST, PUT, DELETE, etc. requests to your server-side APIs. For example, to make a POST request, you can do:
api.post('/my-endpoint', { key: 'value' })
.then(response => console.log(response.data))
.catch(error => console.error(error));
api.post('/my-endpoint', { key: 'value' })
.then(response => console.log(response.data))
.catch(error => console.error(error));
In the above code, replace '/my-endpoint' with the path to your API endpoint and { key: 'value' } with the data you want to send in the request body. Remember to handle the promise returned by api.post() using either .then() and .catch(), or async/await. 3. Define your API on the server-side: On the server-side, you should define your API using the api declaration in your main.wasp file and provide a Node.js implementation for it. For example:
api myEndpoint {
fn: import { myEndpoint } from "@src/apis",
httpRoute: (POST, "/my-endpoint")
}
api myEndpoint {
fn: import { myEndpoint } from "@src/apis",
httpRoute: (POST, "/my-endpoint")
}
And in your src/apis.js file:
export const myEndpoint = (req, res, context) => {
// Your implementation here
};
export const myEndpoint = (req, res, context) => {
// Your implementation here
};
Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Wasp Docs - Using the API from the Client (https://wasp-lang.dev/docs/advanced/apis#using-the-api-from-the-client) - Wasp Docs - Defining the API's NodeJS Implementation (https://wasp-lang.dev/docs/advanced/apis#defining-the-apis-nodejs-implementation) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
Access to XMLHttpRequest at 'http://localhost:3001/api/search' 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. @kapa.ai
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing is related to CORS (Cross-Origin Resource Sharing). This is a security feature that restricts how resources on a web page can be requested from another domain. In your case, your client-side code (running on <http://localhost:3000>) is trying to access a resource on your server (running on <http://localhost:3001>), which is considered a different domain because it's on a different port. To fix this issue, you need to configure your server to allow CORS from your client's domain. If you're using Wasp, you can do this by defining custom middleware for your APIs in the Wasp file. Here's an example:
main.js:
import cors from 'cors'

export const middleware = [
{ name: 'cors', fn: cors() }
]
main.js:
import cors from 'cors'

export const middleware = [
{ name: 'cors', fn: cors() }
]
This will apply the cors middleware to all your APIs, allowing them to accept requests from different domains. After adding this middleware, your server should include the Access-Control-Allow-Origin header in its responses, which will allow your client-side code to access the server's resources. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Wasp Docs - Making Sure CORS Works (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) - Discord support thread: ngrok... (https://discord.com/channels/686873244791210014/1218081390176763914) - Github Issue (open): Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai should i update the main.wasp?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Whether you should update the main.wasp file depends on the changes you're making to your project. Here are a few scenarios where you might need to update it: 1. Adding or updating entities: If you're adding new entities to your project or updating existing ones, you'll need to update the main.wasp file to reflect these changes. 2. Adding or updating routes: If you're adding new routes to your project or updating existing ones, you'll need to update the main.wasp file. 3. Adding or updating actions or queries: If you're adding new actions or queries to your project or updating existing ones, you'll need to update the main.wasp file. 4. Updating Wasp version: If you're updating the version of Wasp you're using, you'll need to update the main.wasp file to reflect the new version. For example, when migrating from Wasp 0.11.X to 0.12.X, you'll need to update the Wasp version field in your main.wasp file to "^0.12.0". 5. Splitting main.wasp file: Currently, Wasp does not support splitting the main.wasp file into separate files. However, this feature is planned for a future update. Remember to always test your changes thoroughly to ensure that everything is working as expected. Sources: - Github Issue (closed): Update wasp version in wasp.cabal in every commit (when needed)? (https://github.com/wasp-lang/wasp/issues/892) - Docs > Migration from 0.11.X to 0.12.X > How to Migrate? > Migrating Your Project to the New Structure Part 4 (https://wasp-lang.dev/docs/migrate-from-0-11-to-0-12#migrating-your-project-to-the-new-structure) - Github Issue (closed): Split file main.wasp (https://github.com/wasp-lang/wasp/issues/656) - Discord support thread: Can I split up the main.wasp file into seperate files (https://discord.com/channels/686873244791210014/1216264399552122922) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai should i update main.wasp when implementing middleware
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, when implementing middleware in a Wasp project, you will need to update the main.wasp file. This is where you specify the middleware configuration for your application. Here's how you can do it: 1. Global Middleware: If you want to modify the middleware for all operations and APIs, you can do so in the main.wasp file. Here's an example:
app todoApp {
// ...

server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
app todoApp {
// ...

server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
2. API-specific Middleware: If you want to modify the middleware for a specific API, you can do so in the main.wasp file. Here's an example:
api webhookCallback {
fn: import { webhookCallback } from "@src/apis",
middlewareConfigFn: import { webhookCallbackMiddlewareFn } from "@src/apis",
httpRoute: (POST, "/webhook/callback"),
auth: false
}
api webhookCallback {
fn: import { webhookCallback } from "@src/apis",
middlewareConfigFn: import { webhookCallbackMiddlewareFn } from "@src/apis",
httpRoute: (POST, "/webhook/callback"),
auth: false
}
3. Per-Path Middleware: If you want to modify the middleware for all API routes under some common path, you can do so in the main.wasp file. Here's an example:
apiNamespace fooBar {
middlewareConfigFn: import { fooBarNamespaceMiddlewareFn } from "@src/apis",
path: "/foo/bar"
}
apiNamespace fooBar {
middlewareConfigFn: import { fooBarNamespaceMiddlewareFn } from "@src/apis",
path: "/foo/bar"
}
Remember to also define the middleware functions in your server-side code (serverSetup.js or apis.js in the examples above). Sources: - Wasp Docs - Customize Global Middleware (https://wasp-lang.dev/docs/advanced/middleware-config#1-customize-global-middleware) - Wasp Docs - Customize api-specific Middleware (https://wasp-lang.dev/docs/advanced/middleware-config#2-customize-api-specific-middleware) - Wasp Docs - Customize Per-Path Middleware (https://wasp-lang.dev/docs/advanced/middleware-config#3-customize-per-path-middleware) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
[ Server!] middlewareConfig.use(cors()); [ Server!] ^ [ Server!] [ Server!] [ Server!] TypeError: middlewareConfig.use is not a function @kapa.ai
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing, TypeError: middlewareConfig.use is not a function, suggests that you're trying to call .use() on middlewareConfig, but middlewareConfig is not an Express application instance. In Wasp, you don't directly use .use() to add middleware. Instead, you define a middleware configuration function that returns an array of middleware. Each middleware is an object with a name and fn (function) property. Here's an example of how you can define a middleware configuration function:
import cors from 'cors'

export const serverMiddlewareFn = () => {
return [
{ name: 'cors', fn: cors() }
]
}
import cors from 'cors'

export const serverMiddlewareFn = () => {
return [
{ name: 'cors', fn: cors() }
]
}
Then, in your main.wasp file, you can specify this function as the middlewareConfigFn for your server:
app MyApp {
// ...
server: {
setupFn: import { mySetupFunction } from "@src/myServerSetupCode.js",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/myServerSetupCode.js"
}
}
app MyApp {
// ...
server: {
setupFn: import { mySetupFunction } from "@src/myServerSetupCode.js",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/myServerSetupCode.js"
}
}
This will apply the cors middleware to all your server-side APIs. Sources: - Wasp Docs - Middleware Configuration (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Project > Server Config (https://wasp-lang.dev/docs/project/server-config) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai /usr/Projects/yt/app/.wasp/out/server/node_modules/express/lib/router/route.js:216 [ Server!] throw new Error(msg); [ Server!] ^ [ Server!] [ Server!] Error: Route.post() requires a callback function but got a [object Object]
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message Route.post() requires a callback function but got a [object Object] typically indicates that Express.js is expecting a callback function for handling a POST route, but it received an object instead. In Wasp, when you define an API endpoint, you need to provide a function that handles the request. This function takes three arguments: req, res, and context. Here's an example:
export const myEndpoint = (req, res, context) => {
// Your implementation here
};
export const myEndpoint = (req, res, context) => {
// Your implementation here
};
Then, in your main.wasp file, you can define the API endpoint like this:
api myEndpoint {
fn: import { myEndpoint } from "@src/apis",
httpRoute: (POST, "/my-endpoint")
}
api myEndpoint {
fn: import { myEndpoint } from "@src/apis",
httpRoute: (POST, "/my-endpoint")
}
Make sure that the function you're importing from @src/apis is indeed a function and not an object. If it's an object, you'll need to adjust your code to ensure that a function is being provided. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Wasp Docs - Defining the API's NodeJS Implementation (https://wasp-lang.dev/docs/advanced/apis#defining-the-apis-nodejs-implementation) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
could it be because i am exporting 2 functions?
MEE6
MEE64mo ago
Wohooo @ArDev, you just became a Waspeteer level 4!
ArDev
ArDevOP4mo ago
@kapa.ai Let me check the knowledge base for you. One moment! 📚 ---------------------- The error message Route.post() requires a callback function but got a [object Object] typically indicates that Express.js is expecting a callback function for handling a POST route, but it received an object instead. In Wasp, when you define an API endpoint, you need to provide a function that handles the request. This function takes three arguments: req, res, and context. Here's an example: export const myEndpoint = (req, res, context) => { // Your implementation here }; Then, in your main.wasp file, you can define the API endpoint like this: api myEndpoint { fn: import { myEndpoint } from "@src/apis", httpRoute: (POST, "/my-endpoint") } Make sure that the function you're importing from @src/apis is indeed a function and not an object. If it's an object, you'll need to adjust your code to ensure that a function is being provided. Sources: Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) Wasp Docs - Defining the API's NodeJS Implementation (https://wasp-lang.dev/docs/advanced/apis#defining-the-apis-nodejs-implementation) ---------------------- Note: you can ask me a follow up question by @ mentioning me again 💬 could it be because i am exporting two functions?
Custom HTTP API Endpoints | Wasp
In Wasp, the default client-server interaction mechanism is through Operations. However, if you need a specific URL method/path, or a specific response, Operations may not be suitable for you. For these cases, you can use an api. Best of all, they should look and feel very familiar.
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, that could be the issue. When you define an API endpoint in Wasp, you should only export a single function that handles the request. If you're exporting multiple functions from the same file, you need to make sure that you're importing the correct one in your main.wasp file. For example, if you have two functions in your apis.js file:
export const myEndpoint = (req, res, context) => {
// Your implementation here
};

export const anotherEndpoint = (req, res, context) => {
// Your implementation here
};
export const myEndpoint = (req, res, context) => {
// Your implementation here
};

export const anotherEndpoint = (req, res, context) => {
// Your implementation here
};
You should import each one separately in your main.wasp file:
api myEndpoint {
fn: import { myEndpoint } from "@src/apis",
httpRoute: (POST, "/my-endpoint")
}

api anotherEndpoint {
fn: import { anotherEndpoint } from "@src/apis",
httpRoute: (POST, "/another-endpoint")
}
api myEndpoint {
fn: import { myEndpoint } from "@src/apis",
httpRoute: (POST, "/my-endpoint")
}

api anotherEndpoint {
fn: import { anotherEndpoint } from "@src/apis",
httpRoute: (POST, "/another-endpoint")
}
If you're still having issues, please double-check your function exports and imports to make sure they match correctly. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Wasp Docs - Defining the API's NodeJS Implementation (https://wasp-lang.dev/docs/advanced/apis#defining-the-apis-nodejs-implementation) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
Yes, that could be the issue. When you define an API endpoint in Wasp, you should only export a single function that handles the request. If you're exporting multiple functions from the same file, you need to make sure that you're importing the correct one in your main.wasp file. For example, if you have two functions in your apis.js file: export const myEndpoint = (req, res, context) => { // Your implementation here }; export const anotherEndpoint = (req, res, context) => { // Your implementation here }; You should import each one separately in your main.wasp file: api myEndpoint { fn: import { myEndpoint } from "@src/apis", httpRoute: (POST, "/my-endpoint") } api anotherEndpoint { fn: import { anotherEndpoint } from "@src/apis", httpRoute: (POST, "/another-endpoint") } If you're still having issues, please double-check your function exports and imports to make sure they match correctly. Sources: Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) Wasp Docs - Defining the API's NodeJS Implementation (https://wasp-lang.dev/docs/advanced/apis#defining-the-apis-nodejs-implementation) ---------------------- Note: you can ask me a follow up question by @ mentioning me again 💬 @kapa.ai i have one function the endpoint and the other the middleware, how do i get around?
Custom HTTP API Endpoints | Wasp
In Wasp, the default client-server interaction mechanism is through Operations. However, if you need a specific URL method/path, or a specific response, Operations may not be suitable for you. For these cases, you can use an api. Best of all, they should look and feel very familiar.
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- If you have one function for the endpoint and another for the middleware, you should define them separately and then import them appropriately in your main.wasp file. Here's an example: In your apis.js file:
// This is your endpoint function
export const myEndpoint = (req, res, context) => {
// Your implementation here
};

// This is your middleware function
export const myMiddleware = (req, res, next) => {
// Your implementation here
next();
};
// This is your endpoint function
export const myEndpoint = (req, res, context) => {
// Your implementation here
};

// This is your middleware function
export const myMiddleware = (req, res, next) => {
// Your implementation here
next();
};
In your main.wasp file:
api myEndpoint {
fn: import { myEndpoint } from "@src/apis",
httpRoute: (POST, "/my-endpoint"),
middlewareConfigFn: import { myMiddleware } from "@src/apis"
}
api myEndpoint {
fn: import { myEndpoint } from "@src/apis",
httpRoute: (POST, "/my-endpoint"),
middlewareConfigFn: import { myMiddleware } from "@src/apis"
}
In this example, myMiddleware is a middleware function that will be applied to the myEndpoint API endpoint. The middlewareConfigFn field in the api declaration is used to specify middleware for that specific API endpoint. Remember that the middleware function should call next() to pass control to the next middleware function in the stack. If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function, otherwise the request will be left hanging. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Wasp Docs - Middleware Configuration (https://wasp-lang.dev/docs/advanced/middleware-config) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai TypeError: modifiedMiddlewareConfig.values is not a function
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message TypeError: modifiedMiddlewareConfig.values is not a function suggests that you're trying to call .values() on modifiedMiddlewareConfig, but modifiedMiddlewareConfig does not have a .values() method. In Wasp, modifiedMiddlewareConfig is a Map object that contains your middleware configuration. The Map object in JavaScript does have a .values() method, which returns a new iterator object that contains the values for each element in the Map object in insertion order. If you're seeing this error, it could mean that modifiedMiddlewareConfig is not a Map object. You might be dealing with a plain JavaScript object or some other data type that does not have a .values() method. Here's an example of how you can iterate over the values in a Map object:
for (let value of modifiedMiddlewareConfig.values()) {
console.log(value);
}
for (let value of modifiedMiddlewareConfig.values()) {
console.log(value);
}
If modifiedMiddlewareConfig is not a Map object, you'll need to adjust your code accordingly. For example, if modifiedMiddlewareConfig is a plain JavaScript object, you can use Object.values() to get an array of its values:
for (let value of Object.values(modifiedMiddlewareConfig)) {
console.log(value);
}
for (let value of Object.values(modifiedMiddlewareConfig)) {
console.log(value);
}
Please double-check your code to make sure you're using the correct methods for the data types you're working with. Sources: - Wasp Docs - Middleware Configuration (https://wasp-lang.dev/docs/advanced/middleware-config) - MDN Web Docs - Map.prototype.values() (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values) - MDN Web Docs - Object.values() (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
Sorry mods ik im prompting a lot 😂 @kapa.ai what is the point in middleware
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Middleware in web development is software that acts as a bridge between an operating system or database and applications, especially on a network. It's essentially a hidden translation layer that sits in the middle of the request-response cycle, processing HTTP requests and responses. In the context of Wasp and other web frameworks, middleware serves several key purposes: 1. Request Processing: Middleware can modify the request object, the response object, or the application's control flow. For example, it can add properties or methods to the request or response objects, or it can end the request-response cycle and send a response to the client. 2. Modularity: Middleware functions are typically small and focused, each doing one specific task. This makes them easy to test, maintain, and reuse. 3. Flexibility: Middleware functions can be plugged into the application's control flow wherever they are needed. They can also be stacked, meaning that you can use multiple middleware functions at the same time, each doing a different task. 4. Control Over Flow: Middleware functions have full control over the request and response objects, and they can decide whether to pass control to the next middleware function in the stack or to end the request-response cycle. In Wasp, middleware can be used for various tasks such as logging, parsing request bodies, handling cookies, and implementing CORS (Cross-Origin Resource Sharing). Wasp also allows you to customize middleware at a global level, per API, or per path. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Support for Permissions (Access Control) (https://github.com/wasp-lang/wasp/issues/584) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai i implemented a middleware through - export const searchMiddlewareConfig = (middlewareConfig) => { console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw') middlewareConfig.delete('express.json') return middlewareConfig } but i still get youtube-search:1 Access to XMLHttpRequest at 'http://localhost:3001/api/search' 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.
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing is related to Cross-Origin Resource Sharing (CORS). It appears that your server is not sending the necessary Access-Control-Allow-Origin header in its response. This header is required for the browser to allow your web page to make a request to a server that's on a different origin (domain, scheme, or port). In your middleware configuration function, you're deleting the 'express.json' middleware, but you're not adding any middleware to handle CORS. To resolve this issue, you need to add CORS middleware to your configuration. Here's an example of how you can do this:
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors()) // Add this line

return middlewareConfig
}
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors()) // Add this line

return middlewareConfig
}
This will add the cors middleware to your configuration, which will add the necessary Access-Control-Allow-Origin header to your server's responses. Please note that this is a basic setup that will allow requests from any origin. Depending on your needs, you might want to configure cors to restrict which origins are allowed. You can do this by passing an options object to the cors() function. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai The error message you're seeing is related to Cross-Origin Resource Sharing (CORS). It appears that your server is not sending the necessary Access-Control-Allow-Origin header in its response. This header is required for the browser to allow your web page to make a request to a server that's on a different origin (domain, scheme, or port). In your middleware configuration function, you're deleting the 'express.json' middleware, but you're not adding any middleware to handle CORS. To resolve this issue, you need to add CORS middleware to your configuration. Here's an example of how you can do this: import cors from 'cors' export const searchMiddlewareConfig = (middlewareConfig) => { console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw') middlewareConfig.delete('express.json') middlewareConfig.set('cors', cors()) // Add this line return middlewareConfig } This will add the cors middleware to your configuration, which will add the necessary Access-Control-Allow-Origin header to your server's responses. Please note that this is a basic setup that will allow requests from any origin. Depending on your needs, you might want to configure cors to restrict which origins are allowed. You can do this by passing an options object to the cors() function. i still did this but i am still getting - Access to XMLHttpRequest at 'http://localhost:3001/api/search' 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. sear.tsx:47 Error searching comments: AxiosError handleSearch @ sear.tsx:47 sear.tsx:55 Detailed error: { "message": "Network Error", "name": "AxiosError", "stack": "AxiosError: Network Error\n at XMLHttpRequest.handleError (
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing is related to Cross-Origin Resource Sharing (CORS). It appears that your server is not sending the necessary Access-Control-Allow-Origin header in its response. This header is required for the browser to allow your web page to make a request to a server that's on a different origin (domain, scheme, or port). In your middleware configuration function, you're deleting the 'express.json' middleware, but you're not adding any middleware to handle CORS. To resolve this issue, you need to add CORS middleware to your configuration. Here's an example of how you can do this:
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors()) // Add this line

return middlewareConfig
}
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors()) // Add this line

return middlewareConfig
}
This will add the cors middleware to your configuration, which will add the necessary Access-Control-Allow-Origin header to your server's responses. Please note that this is a basic setup that will allow requests from any origin. Depending on your needs, you might want to configure cors to restrict which origins are allowed. You can do this by passing an options object to the cors() function. If you're still encountering the issue after adding the cors middleware, it could be due to some other configuration in your server or client code. You might want to check the following: 1. Server Setup: Ensure that your server is correctly set up to use the middleware configuration function. In your main.wasp file, you should have something like this:
app MyApp {
// ...
server: {
setupFn: import { setup } from "@src/serverSetup",
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup"
}
}
app MyApp {
// ...
server: {
setupFn: import { setup } from "@src/serverSetup",
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup"
}
}
2. Client Setup: Ensure that your client is correctly set up to make requests to the server. If you're using axios, you might need to set the withCredentials option to true to include cookies in the request. This is necessary for CORS requests if you're using sessions or HTTP authentication.
axios.post('/api/search', data, { withCredentials: true })
axios.post('/api/search', data, { withCredentials: true })
3. CORS Configuration: If you're restricting which origins are allowed in your cors configuration, ensure that the origin of your client is included in the list.
middlewareConfig.set('cors', cors({ origin: '<http://localhost:3000'> }))
middlewareConfig.set('cors', cors({ origin: '<http://localhost:3000'> }))
Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Support for Permissions (Access Control) (https://github.com/wasp-lang/wasp/issues/584) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai i am using api.post api being - import { api } from 'wasp/client/api'; The error message you're seeing is related to Cross-Origin Resource Sharing (CORS). It appears that your server is not sending the necessary Access-Control-Allow-Origin header in its response. This header is required for the browser to allow your web page to make a request to a server that's on a different origin (domain, scheme, or port). Please note that this is a basic setup that will allow requests from any origin. Depending on your needs, you might want to configure cors to restrict which origins are allowed. You can do this by passing an options object to the cors() function. If you're still encountering the issue after adding the cors middleware, it could be due to some other configuration in your server or client code. You might want to check the following: Server Setup: Ensure that your server is correctly set up to use the middleware configuration function. In your main.wasp file, you should have something like this: app MyApp { // ... server: { setupFn: import { setup } from "@src/serverSetup", middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup" } } Client Setup: Ensure that your client is correctly set up to make requests to the server. If you're using axios, you might need to set the withCredentials option to true to include cookies in the request. This is necessary for CORS requests if you're using sessions or HTTP authentication. axios.post('/api/search', data, { withCredentials: true }) CORS Configuration: If you're restricting which origins are allowed in your cors configuration, ensure that the origin of your client is included in the list. middlewareConfig.set('cors', cors({ origin: 'http://localhost:3000' }))
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing is related to Cross-Origin Resource Sharing (CORS). It appears that your server is not sending the necessary Access-Control-Allow-Origin header in its response. This header is required for the browser to allow your web page to make a request to a server that's on a different origin (domain, scheme, or port). To resolve this issue, you need to add CORS middleware to your configuration. Here's an example of how you can do this:
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors()) // Add this line

return middlewareConfig
}
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors()) // Add this line

return middlewareConfig
}
This will add the cors middleware to your configuration, which will add the necessary Access-Control-Allow-Origin header to your server's responses. Please note that this is a basic setup that will allow requests from any origin. Depending on your needs, you might want to configure cors to restrict which origins are allowed. You can do this by passing an options object to the cors() function. If you're still encountering the issue after adding the cors middleware, it could be due to some other configuration in your server or client code. You might want to check the following: 1. Server Setup: Ensure that your server is correctly set up to use the middleware configuration function. In your main.wasp file, you should have something like this:
app MyApp {
// ...
server: {
setupFn: import { setup } from "@src/serverSetup",
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup"
}
}
app MyApp {
// ...
server: {
setupFn: import { setup } from "@src/serverSetup",
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup"
}
}
2. Client Setup: Ensure that your client is correctly set up to make requests to the server. If you're using axios, you might need to set the withCredentials option to true to include cookies in the request. This is necessary for CORS requests if you're using sessions or HTTP authentication.
axios.post('/api/search', data, { withCredentials: true })
axios.post('/api/search', data, { withCredentials: true })
3. CORS Configuration: If you're restricting which origins are allowed in your cors configuration, ensure that the origin of your client is included in the list.
middlewareConfig.set('cors', cors({ origin: '<http://localhost:3000'> }))
middlewareConfig.set('cors', cors({ origin: '<http://localhost:3000'> }))
Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Support for Permissions (Access Control) (https://github.com/wasp-lang/wasp/issues/584) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai i am doing api.post (import { api } from 'wasp/client/api';) instead of axios.post is this fine?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, using api.post is absolutely fine. In fact, it's the recommended way to make HTTP requests in a Wasp application. The api object you're importing from 'wasp/client/api' is a pre-configured instance of axios. It's set up to make requests to your server, and it includes support for sending and receiving authentication tokens. Here's an example of how you can use api.post:
import { api } from 'wasp/client/api'

const data = { /* your data here */ }

api.post('/api/search', data)
.then(response => {
console.log(response.data)
})
.catch(error => {
console.error(error)
})
import { api } from 'wasp/client/api'

const data = { /* your data here */ }

api.post('/api/search', data)
.then(response => {
console.log(response.data)
})
.catch(error => {
console.error(error)
})
This will send a POST request to the /api/search endpoint on your server, with the specified data as the request body. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis#using-the-api-from-the-client) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai but i still get the error
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- I'm sorry to hear that you're still encountering the CORS issue. This can be a tricky problem to debug because it involves both the server and the client. Here are a few more things you can try: 1. Check Your Middleware Configuration: Make sure that your middleware configuration function is correctly set up and is being used by your server. You should see the console log message 'webhookCallbackMiddlewareFn: Swap express.json for express.raw' when your server starts. If you don't see this message, it means that your middleware configuration function is not being used. 2. Check Your CORS Configuration: If you're restricting which origins are allowed in your cors configuration, make sure that the origin of your client is included in the list. The origin should match the domain, scheme, and port of your client. For example, if your client is running on <http://localhost:3000,> your CORS configuration should allow this origin. 3. Check Your Client Code: Make sure that your client code is correctly set up to make requests to your server. If you're using the api object from 'wasp/client/api', you should be able to make requests to your server without having to worry about CORS, because the api object is pre-configured to handle CORS. 4. Check Your Server Code: Make sure that your server code is correctly set up to handle requests from your client. If your server is not correctly set up to handle CORS, it might not send the necessary Access-Control-Allow-Origin header in its responses. 5. Check Your Network: Sometimes, network issues or firewalls can interfere with CORS. Try running your client and server on the same machine to see if the problem persists. If you're still encountering the issue after trying these steps, it might be helpful to provide more information about your setup. For example, what versions of Wasp, Node.js, and other relevant software are you using? What does your client code look like? What does your server code look like? This information can help others to better understand your problem and provide more specific advice. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Support for Permissions (Access Control) (https://github.com/wasp-lang/wasp/issues/584) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
Check Your Client Code: Make sure that your client code is correctly set up to make requests to your server. If you're using the api object from 'wasp/client/api', you should be able to make requests to your server without having to worry about CORS, because the api object is pre-configured to handle CORS. @kapa.ai but i still gets cors errors? import { api } from 'wasp/client/api'; const response = await api.post('/api/search', { apiKey, channelInput, query })
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- I'm sorry to hear that you're still encountering CORS issues. The api.post method from 'wasp/client/api' should indeed handle CORS correctly, as it's pre-configured to do so. However, CORS is a browser mechanism that prevents requests to different origins, and it's handled at the server level. Even though the api object is set up to handle CORS, the server also needs to be correctly configured to accept cross-origin requests. Here are a few more things you can check: 1. Server-side CORS Configuration: Ensure that your server is correctly set up to handle CORS. This typically involves setting the Access-Control-Allow-Origin header to the origin of your client. In Wasp, you can do this by adding a CORS middleware to your server configuration. Here's an example:
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}
This will add the cors middleware to your server configuration, which will add the necessary Access-Control-Allow-Origin header to your server's responses. 2. Check the Network Tab in Developer Tools: Open the developer tools in your browser and go to the Network tab. Find the request that's causing the CORS error, click on it, and check the Headers tab. Look for the Access-Control-Allow-Origin header in the response headers. If it's not there, or if it doesn't match the origin of your client, that's likely the cause of the CORS error. 3. Check for Server Errors: Sometimes, a server error can cause a CORS error. If there's an error in your server code, the server might not send the correct response headers, which can cause a CORS error. Check your server logs for any errors. If you're still encountering the issue after trying these steps, it might be a good idea to ask for help on the Wasp Github Discussions (https://github.com/wasp-lang/wasp/discussions) or Wasp Discord server (https://discord.gg/rzdnErX). The Wasp community and maintainers are usually very helpful and might be able to provide more specific advice. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai 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. but here is my code - export const searchMiddlewareConfig = (middlewareConfig) => { console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw') middlewareConfig.delete('express.json') middlewareConfig.set('cors', cors()) // Add this line return middlewareConfig } api searchApi { fn: import { search } from "@src/server/main/actions.js", httpRoute: (POST, "/api/search"), middlewareConfigFn: import { searchMiddlewareConfig } from "@src/server/main/actions.js" }
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Your code seems to be correctly set up for handling CORS. You have the cors middleware added in your searchMiddlewareConfig function, and you're using this function in your searchApi definition. However, if you're still encountering CORS issues, it could be due to some other factors. Here are a few things you can check: 1. CORS Configuration: The cors() function can take an options object to customize its behavior. If you're not passing any options, it will allow requests from any origin. If you need to restrict which origins are allowed, you can do so by passing an options object. For example:
middlewareConfig.set('cors', cors({ origin: '<http://localhost:3000'> }))
middlewareConfig.set('cors', cors({ origin: '<http://localhost:3000'> }))
This will only allow requests from <http://localhost:3000.> 2. Server Setup: Make sure that your server is correctly set up to use the middleware configuration function. In your main.wasp file, you should have something like this:
app MyApp {
// ...
server: {
setupFn: import { setup } from "@src/serverSetup",
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup"
}
}
app MyApp {
// ...
server: {
setupFn: import { setup } from "@src/serverSetup",
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup"
}
}
3. Client Code: Make sure that your client code is correctly set up to make requests to your server. If you're using the api object from 'wasp/client/api', you should be able to make requests to your server without having to worry about CORS, because the api object is pre-configured to handle CORS. If you're still encountering the issue after checking these things, it might be a good idea to ask for help on the Wasp Github Discussions (https://github.com/wasp-lang/wasp/discussions) or Wasp Discord server (https://discord.gg/rzdnErX). The Wasp community and maintainers are usually very helpful and might be able to provide more specific advice. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
api searchApi { fn: import { search } from "@src/server/main/actions.js", httpRoute: (POST, "/api/search"), middlewareConfigFn: import { searchMiddlewareConfig } from "@src/server/main/actions.js" } @kapa.ai is this correct main.wasp config? there is no server: {} in min
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, your api configuration in the main.wasp file looks correct. You have correctly imported the function search from @src/server/main/actions.js and set it as the function for the searchApi. You have also correctly set the HTTP route to (POST, "/api/search") and imported the searchMiddlewareConfig function for the middleware configuration. However, if you want to apply the searchMiddlewareConfig globally to all your APIs and operations, you should include it in the server field in your main.wasp file like this:
app MyApp {
// ...
server: {
setupFn: import { setup } from "@src/serverSetup",
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup"
}
}
app MyApp {
// ...
server: {
setupFn: import { setup } from "@src/serverSetup",
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/serverSetup"
}
}
If you don't include the server field, the searchMiddlewareConfig will only apply to the searchApi. Please note that the setupFn and middlewareConfigFn are optional fields. If you don't need any custom setup for your server, you can omit the setupFn. Similarly, if you don't need any custom middleware configuration, you can omit the middlewareConfigFn. Sources: - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Server Config (https://wasp-lang.dev/docs/project/server-config) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai what are all the possible ways for cors issues - Access to XMLHttpRequest at 'http://localhost:3001/api/search' 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. YoutubeSearch.tsx:47 Error searching comments: AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} handleSearch @ Search.tsx:47 await in handleSearch callCallback2 @ chunk-6BKLQ22S.js?v=836caa30:3674 invokeGuardedCallbackDev @ chunk-6BKLQ22S.js?v=836caa30:3699 invokeGuardedCallback @ chunk-6BKLQ22S.js?v=836caa30:3733 invokeGuardedCallbackAndCatchFirstError @ chunk-6BKLQ22S.js?v=836caa30:3736 executeDispatch @ chunk-6BKLQ22S.js?v=836caa30:7014 processDispatchQueueItemsInOrder @ chunk-6BKLQ22S.js?v=836caa30:7034 processDispatchQueue @ chunk-6BKLQ22S.js?v=836caa30:7043 dispatchEventsForPlugins @ chunk-6BKLQ22S.js?v=836caa30:7051 (anonymous) @ chunk-6BKLQ22S.js?v=836caa30:7174 batchedUpdates$1 @ chunk-6BKLQ22S.js?v=836caa30:18913 batchedUpdates @ chunk-6BKLQ22S.js?v=836caa30:3579 dispatchEventForPluginEventSystem @ chunk-6BKLQ22S.js?v=836caa30:7173 dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ chunk-6BKLQ22S.js?v=836caa30:5478 dispatchEvent @ chunk-6BKLQ22S.js?v=836caa30:5472 dispatchDiscreteEvent @ chunk-6BKLQ22S.js?v=836caa30:5449
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- CORS (Cross-Origin Resource Sharing) issues typically occur when a web application tries to make a request to a server that's on a different origin (domain, scheme, or port) than the web application itself. The error message you're seeing indicates that the server at <http://localhost:3001> is not sending the necessary Access-Control-Allow-Origin header in its response to the preflight request from the origin <http://localhost:3000.> Here are some possible reasons for CORS issues: 1. Server Configuration: The server needs to include the Access-Control-Allow-Origin header in its responses. This header tells the browser which origins are allowed to access the server's resources. If this header is missing, or if it doesn't include the origin of the web application, the browser will block the request. 2. Preflight Requests: Some types of requests (like POST requests with a JSON body) trigger a preflight request. This is an automatic OPTIONS request sent by the browser to check if the server will allow the actual request. If the server doesn't respond correctly to the preflight request, the browser will block the actual request. 3. Middleware Configuration: If you're using Express.js or a similar framework, you might need to use middleware to handle CORS. For example, the cors middleware in Express.js can be used to automatically add the Access-Control-Allow-Origin header to responses. 4. Network Issues: Sometimes, network issues or firewalls can interfere with CORS. If the server's response is modified or blocked by a network issue or firewall, the browser might not receive the Access-Control-Allow-Origin header. 5. Browser Extensions: Some browser extensions can interfere with CORS. If you have any extensions that modify requests or responses, try disabling them to see if that resolves the issue. To resolve your issue, you need to ensure that your server is correctly set up to handle CORS. This typically involves adding the cors middleware to your server configuration and ensuring that it's correctly set up to handle preflight requests. Here's an example of how you can add the cors middleware in Wasp:
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {{
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}}
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {{
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}}
This will add the cors middleware to your server configuration, which will add the necessary Access-Control-Allow-Origin header to your server's responses. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
Preflight Requests: Some types of requests (like POST requests with a JSON body) trigger a preflight request. This is an automatic OPTIONS request sent by the browser to check if the server will allow the actual request. If the server doesn't respond correctly to the preflight request, the browser will block the actual request. @kapa.ai how do i do this
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- In most cases, you don't need to manually handle preflight requests. If you're using Express.js or a similar framework with the cors middleware, it will automatically handle preflight requests for you. Here's an example of how you can add the cors middleware in Wasp:
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}
import cors from 'cors'

export const searchMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}
This will add the cors middleware to your server configuration, which will automatically handle preflight OPTIONS requests. It will send a response with the necessary Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers, which tell the browser that it's allowed to make the actual request. If you need to handle preflight requests manually for some reason, you can do so by adding a handler for OPTIONS requests. Here's an example:
app.options('*', (req, res) => {
res.set('Access-Control-Allow-Origin', '*')
res.set('Access-Control-Allow-Methods', 'GET, POST')
res.set('Access-Control-Allow-Headers', 'Content-Type')
res.send()
})
app.options('*', (req, res) => {
res.set('Access-Control-Allow-Origin', '*')
res.set('Access-Control-Allow-Methods', 'GET, POST')
res.set('Access-Control-Allow-Headers', 'Content-Type')
res.send()
})
This will respond to any OPTIONS request with the necessary CORS headers. However, this is usually not necessary if you're using the cors middleware. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai [ Server ] webhookCallbackMiddlewareFn: Swap express.json for express.raw
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- It seems like you want to replace the express.json middleware with express.raw for a specific route in your Wasp application. This is typically done when you want to handle raw, binary data in your request bodies, instead of JSON data. Here's how you can do this in Wasp:
import express from 'express'

export const webhookCallbackMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('express.raw', express.raw())

return middlewareConfig
}
import express from 'express'

export const webhookCallbackMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('express.raw', express.raw())

return middlewareConfig
}
In this code, webhookCallbackMiddlewareConfig is a function that modifies the middleware configuration for a specific route. It removes the express.json middleware and adds the express.raw middleware. You can then use this function in your api definition in the main.wasp file:
api webhookCallbackApi {
fn: import { webhookCallback } from "@src/server/main/actions.js",
httpRoute: (POST, "/api/webhookCallback"),
middlewareConfigFn: import { webhookCallbackMiddlewareConfig } from "@src/server/main/actions.js"
}
api webhookCallbackApi {
fn: import { webhookCallback } from "@src/server/main/actions.js",
httpRoute: (POST, "/api/webhookCallback"),
middlewareConfigFn: import { webhookCallbackMiddlewareConfig } from "@src/server/main/actions.js"
}
This will apply the webhookCallbackMiddlewareConfig function to the webhookCallbackApi, so requests to /api/webhookCallback will be handled with express.raw instead of express.json. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai Access to XMLHttpRequest at 'http://localhost:3001/api/search' 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. this happens the output when it reloads [Server ] webhookCallbackMiddlewareFn: Swap express.json for express.raw this is my code - export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => { console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw') middlewareConfig.delete('express.json') middlewareConfig.set('express.raw', express.raw()) // Add this line return middlewareConfig }
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The CORS issue you're encountering is due to the server at <http://localhost:3001> not sending the necessary Access-Control-Allow-Origin header in its response. This header tells the browser which origins are allowed to access the server's resources. If this header is missing, or if it doesn't include the origin of the web application, the browser will block the request. In your code, you're swapping express.json middleware for express.raw middleware. However, to solve the CORS issue, you need to add the cors middleware to your server configuration. Here's how you can modify your middleware configuration function to include cors:
import cors from 'cors'
import express from 'express'

export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('express.raw', express.raw())
middlewareConfig.set('cors', cors()) // Add this line

return middlewareConfig
}
import cors from 'cors'
import express from 'express'

export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')

middlewareConfig.delete('express.json')
middlewareConfig.set('express.raw', express.raw())
middlewareConfig.set('cors', cors()) // Add this line

return middlewareConfig
}
This will add the cors middleware to your server configuration, which will automatically handle preflight OPTIONS requests and add the necessary Access-Control-Allow-Origin header to your server's responses. Please note that the cors middleware should be added before any other middleware that needs to handle CORS, to ensure that it can add the necessary headers to the response. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
Debug Information:
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message indicates that there's a network error when your application tries to make a request to <http://localhost:3001/api/search-youtube-comments.> This could be due to several reasons: 1. Server is not running: Make sure that your server is running and listening on the correct port (3001 in this case). 2. Incorrect URL: Ensure that the URL /api/search-youtube-comments is correct and that your server has a route handler for this URL. 3. Network issues: There might be issues with your network that are preventing the request from reaching the server. Try checking your network connection and firewall settings. 4. CORS issues: If your client and server are on different origins (which is the case here since your client is on <http://localhost:3000> and your server is on <http://localhost:3001>), you might encounter CORS (Cross-Origin Resource Sharing) issues. Make sure that your server is correctly set up to handle CORS. Here's how you can add the cors middleware in Wasp to handle CORS:
import cors from 'cors'

export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}
import cors from 'cors'

export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}
This will add the cors middleware to your server configuration, which will automatically handle preflight OPTIONS requests and add the necessary Access-Control-Allow-Origin header to your server's responses. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai how can i make it on port 3000 and remove port 3001
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- In Wasp, the development server uses two ports by default: 3000 for the client (frontend) and 3001 for the server (backend). This is hardcoded and currently cannot be changed to use a single port. However, there is an open issue on the Wasp GitHub repository to make it easy to use different ports during Wasp development. This includes the ability to manually specify different ports or have Wasp dynamically search for open ports. You can follow the progress of this issue here (https://github.com/wasp-lang/wasp/issues/730). If you have a process running on port 3000 or 3001 that is causing conflicts, you can terminate that process and then run wasp start again. If you're on a Unix-based system, you can use the fuser command to kill the process running on a specific port:
fuser -k 3000/tcp
fuser -k 3001/tcp
fuser -k 3000/tcp
fuser -k 3001/tcp
After running these commands, you should be able to start your Wasp app without any port conflicts. Sources: - Github Issue - Make it easy to use different ports (than 3000 and 3001) during Wasp development (https://github.com/wasp-lang/wasp/issues/730) - Github Issue - Process is already running on port 3000 (https://github.com/wasp-lang/wasp/issues/198) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai why do i still get cors issues but i have middleware set up?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- CORS (Cross-Origin Resource Sharing) issues can occur due to several reasons, even if you have set up the cors middleware. Here are a few possible reasons: 1. Middleware Order: The order in which middleware is applied in Express matters. The cors middleware should be applied before any other middleware that needs to handle CORS. If it's not, the necessary CORS headers might not be set correctly. 2. Incorrect Configuration: The cors middleware might not be configured correctly. For example, the origin option in the cors middleware determines which origins are allowed to access the server's resources. If this option is not set correctly, you might still encounter CORS issues. 3. Preflight Requests: Some types of requests (like POST requests with a JSON body) trigger a preflight request. This is an automatic OPTIONS request sent by the browser to check if the server will allow the actual request. If the server doesn't respond correctly to the preflight request, the browser will block the actual request. Here's how you can add the cors middleware in Wasp:
import cors from 'cors'

export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}
import cors from 'cors'

export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}
This will add the cors middleware to your server configuration, which will automatically handle preflight OPTIONS requests and add the necessary Access-Control-Allow-Origin header to your server's responses. If you're still encountering CORS issues after checking these points, it might be helpful to provide more details about your setup and the exact error message you're seeing. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
server: { middlewares: [ import { serverSetup } from "@src/server/serverSetup.js" ] }, @kapa.ai this correct? Parse error: Unexpected token:
Expected one of the following tokens instead: <eof> 97 | entity User {=psl 98 | id Int @id @default(autoincrement()) 99 | createdAt DateTime @default(now()) ❌ --- [Error] Recompilation on file change failed.: ------------------------------
MEE6
MEE64mo ago
Wohooo @ArDev, you just became a Waspeteer level 5!
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The code you provided seems to be incorrect. In Wasp, the server field of the app declaration is used to configure the behavior of the server. It should be a dictionary with the fields setupFn and middlewareConfigFn, not an array of middlewares. Here's how you can correctly configure the server in your main.wasp file:
app MyApp {
title: "My app",
// ...
server: {
setupFn: import { serverSetup } from "@src/server/serverSetup.js"
}
}
app MyApp {
title: "My app",
// ...
server: {
setupFn: import { serverSetup } from "@src/server/serverSetup.js"
}
}
In this code, serverSetup is a function that will be executed on server start. This function is expected to be async and will be awaited before the server starts accepting any requests. If you want to configure middleware, you should use the middlewareConfigFn field:
app MyApp {
title: "My app",
// ...
server: {
setupFn: import { serverSetup } from "@src/server/serverSetup.js",
middlewareConfigFn: import { myMiddlewareConfigFn } from "@src/server/serverSetup.js"
}
}
app MyApp {
title: "My app",
// ...
server: {
setupFn: import { serverSetup } from "@src/server/serverSetup.js",
middlewareConfigFn: import { myMiddlewareConfigFn } from "@src/server/serverSetup.js"
}
}
In this code, myMiddlewareConfigFn is a function that modifies the middleware configuration for the server. Sources: - Wasp Docs - Server Config (https://wasp-lang.dev/docs/project/server-config) - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai @tanstack_react-query.js?v=836caa30:1020 Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["auth/me"] @tanstack_react-query.js?v=836caa30:1005 Error: ["auth/me"] data is undefined at Object.onSuccess (@tanstack_react-quer…?v=836caa30:1022:19) at resolve (@tanstack_react-quer…s?v=836caa30:603:50) @tanstack_react-query.js?v=836caa30:1020 Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["auth/me"] @tanstack_react-query.js?v=836caa30:1005 Error: ["auth/me"] data is undefined at Object.onSuccess (@tanstack_react-quer…?v=836caa30:1022:19) at resolve (@tanstack_react-quer…s?v=836caa30:603:50)
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing is from React Query, a library used for fetching, caching, and updating asynchronous data in React. The error is saying that the data returned from a query with the key auth/me is undefined. In Wasp, the auth/me endpoint is used to check the current authentication status of the user. If the user is authenticated, it returns the user's session data. If the user is not authenticated, it returns a 401 Unauthorized status code. The error could be due to several reasons: 1. The server is not returning any data: If the server doesn't return any data for the auth/me endpoint, React Query will throw this error. Make sure your server is correctly set up to handle the auth/me request and return the appropriate data. 2. The server is returning an error status code: If the server returns a 401 Unauthorized status code, the client might interpret this as the server not returning any data, causing React Query to throw this error. You might need to adjust your client code to correctly handle this status code. 3. The query function is not returning any data: If the query function you're using with React Query doesn't return any data, React Query will throw this error. Make sure your query function is correctly set up to return the data from the auth/me request. Without more information about your setup, it's hard to provide a more specific solution. However, you might find it helpful to review the Wasp authentication docs (https://wasp-lang.dev/docs/guides/auth) and the React Query docs (https://react-query.tanstack.com/overview) for more information. Sources: - Github Issue - Discuss how we use authentication (https://github.com/wasp-lang/wasp/issues/566) - Wasp Docs - Authentication (https://wasp-lang.dev/docs/guides/auth) - React Query Docs - Overview (https://react-query.tanstack.com/overview) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. list all possible solutions, it says my server is listening
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing is related to Cross-Origin Resource Sharing (CORS). This is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. Here are some possible solutions: 1. Add CORS Middleware: In Wasp, you can add the cors middleware to your server configuration. This middleware will automatically handle preflight OPTIONS requests and add the necessary Access-Control-Allow-Origin header to your server's responses. Here's how you can add the cors middleware:
import cors from 'cors'

export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}

import cors from 'cors'

export const searchYoutubeCommentsMiddlewareConfig = (middlewareConfig) => {
middlewareConfig.delete('express.json')
middlewareConfig.set('cors', cors())
return middlewareConfig
}

Source: Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) 2. Check Middleware Order: The order in which middleware is applied in Express matters. The cors middleware should be applied before any other middleware that needs to handle CORS. If it's not, the necessary CORS headers might not be set correctly. 3. Check CORS Configuration: The cors middleware might not be configured correctly. For example, the origin option in the cors middleware determines which origins are allowed to access the server's resources. If this option is not set correctly, you might still encounter CORS issues. 4. Handle Preflight Requests: Some types of requests (like POST requests with a JSON body) trigger a preflight request. This is an automatic OPTIONS request sent by the browser to check if the server will allow the actual request. If the server doesn't respond correctly to the preflight request, the browser will block the actual request. 5. Check Server Response: Make sure your server is correctly set up to handle the request and return the appropriate response. The server should include the Access-Control-Allow-Origin header in its response. 6. Check Network Issues: There might be issues with your network that are preventing the request from reaching the server. Try checking your network connection and firewall settings. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@IamIconLiving 🏀 how do you deal with CORS issues i have middleware
api searchApi {
fn: import { search } from "@src/server/main/actions.js",
entities: [User],
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/server/main/actions.js",
httpRoute: (POST, "/api/search")
}
api searchApi {
fn: import { search } from "@src/server/main/actions.js",
entities: [User],
middlewareConfigFn: import { searchMiddlewareConfig } from "@src/server/main/actions.js",
httpRoute: (POST, "/api/search")
}
@kapa.ai AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:3000/node_modules/.vite/deps/axios.js?v=836caa30:1439:14)\n at Axios.request (http://localhost:3000/node_modules/.vite/deps/axios.js?v=836caa30:1769:41)\n at async handleSearch (http://localhost:3000/@fs/usr/Projects/yt/app/src/client/pages/Search.tsx:48:24)",
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing is from Axios, a promise-based HTTP client for the browser and Node.js. The error message AxiosError: Network Error typically means that the request could not be made due to issues with the network. Here are some possible reasons for this error: 1. Server is not running: Make sure that your server is running and listening on the correct port. 2. Incorrect URL: The URL you're trying to reach might be incorrect. Check the URL and make sure it's correct. 3. Network Issues: There might be issues with your network that are preventing the request from reaching the server. Try checking your network connection and firewall settings. 4. CORS Issues: If you're making a request to a different origin, you might be running into Cross-Origin Resource Sharing (CORS) issues. Make sure your server is set up to handle CORS. Without more information about your setup and the exact line of code causing the error, it's hard to provide a more specific solution. However, you might find it helpful to review the Axios documentation (https://axios-http.com/docs/intro) for more information on how to handle errors with Axios. If you're using Wasp and encountering this error, you might also find the Wasp documentation (https://wasp-lang.dev/docs) helpful, particularly the sections on making API requests (https://wasp-lang.dev/docs/guides/apis) and configuring middleware (https://wasp-lang.dev/docs/advanced/middleware-config) for handling CORS. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai could authentication post & get cause issues ?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, issues can arise with POST and GET requests related to authentication in certain scenarios. Here are a few possibilities: 1. Incorrect Credentials: If the credentials provided in a POST request to an authentication endpoint are incorrect, the server will respond with an error. This could be a 401 Unauthorized status code, indicating that the provided credentials are not valid. 2. Session Expiry: If a user's session has expired, a GET request to an endpoint that requires authentication could fail. The server might respond with a 401 Unauthorized status code in this case. 3. CORS Issues: Cross-Origin Resource Sharing (CORS) issues can occur when making POST or GET requests to an authentication endpoint from a different origin. The server needs to be correctly configured to handle CORS. 4. Server Errors: If there's an issue on the server-side (like a database error), POST and GET requests to authentication endpoints could fail. 5. Misuse of Endpoints: As discussed in the Github Issue - Discuss how we use authentication (https://github.com/wasp-lang/wasp/issues/566), using the same endpoint for checking whether the user is authenticated and for retrieving the session can lead to issues. If the endpoint returns an error when the user is not authenticated, this could be interpreted as a client-side error, even though it's part of the client's regular procedure for determining whether the user has a session. 6. Browser Behavior: As mentioned in the Discord support thread: Auth kicking out (https://discord.com/channels/686873244791210014/1217167281612656751), certain browser behaviors, like switching between tabs, can cause unexpected logouts if the authentication status is not handled correctly. Remember, the exact issues and their solutions can vary depending on the specifics of your application and its authentication setup. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
ArDev
ArDevOP4mo ago
@kapa.ai could authentication post & get cause CORS issues for other apis auth seems to be working but for other apis it is not?
kapa.ai
kapa.ai4mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- Yes, it's possible that authentication-related POST and GET requests could cause CORS issues for other APIs. Here's why: 1. CORS Configuration: If your server is configured to only allow CORS for specific routes (like your authentication routes), then other routes (like your other APIs) might not have the necessary CORS headers, causing browsers to block requests to those routes. 2. Preflight Requests: Some types of requests (like POST requests with a JSON body) trigger a preflight request. This is an automatic OPTIONS request sent by the browser to check if the server will allow the actual request. If the server doesn't respond correctly to the preflight request, the browser will block the actual request. This could be happening with your other APIs. 3. Authorization Headers: If you're setting an Authorization header for your authenticated requests, and your server is not configured to allow this header in CORS requests, then browsers will block requests that include this header. This could be affecting your other APIs if they also require authentication. To resolve these issues, you'll need to ensure that your server is correctly configured to handle CORS for all necessary routes, not just your authentication routes. This includes responding correctly to preflight requests and allowing necessary headers. In Wasp, you can configure CORS by defining custom middleware for your APIs in the Wasp file. Here's an example:
import cors from 'cors'

export const apiMiddleware = (config) => {
return config.set('cors', cors())
}
import cors from 'cors'

export const apiMiddleware = (config) => {
return config.set('cors', cors())
}
This will add the cors middleware to your server configuration, which will automatically handle preflight OPTIONS requests and add the necessary Access-Control-Allow-Origin header to your server's responses. Sources: - Wasp Docs - Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config) - Wasp Docs - Custom HTTP API Endpoints (https://wasp-lang.dev/docs/advanced/apis) - Github Issue - Api.post on custom HTTP Endpoint results in CORS Error (https://github.com/wasp-lang/wasp/issues/1757) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @ArDev, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Want results from more Discord servers?
Add your server