{data.email}
2014.06.28 06:29 Confusing Perspectives
2015.04.29 08:35 TWICE (트와이스)
2013.08.14 15:08 andreasw Antiwork: Unemployment for all, not just the rich!
2024.03.19 22:19 EricLeib New library for simplifying API specs in full-stack typescript projects
const user = z.object({ firstName: z.string(), lastName: z.string(), });
const createUser = operation({ method: 'POST', body: user }); const getUser = operation({ method: 'GET', path: '/{userId}', routeParams: z.object({userId: z.coerce.number(),}), response: z.array(user), }); const getUsers = operation({ method: 'GET', queryParams: z.object({userId: z.coerce.number()}).optional(), response: z.array(user), });
const userResource = { path: '/users', tags: ['Users'], operations: { createUser, getUser, getUsers } }From there, you get 3-for-1:
@Api(userResource) // This automatically maps all the routes below @Controller() class MyController implements ApiServiceHere is a gist with a full example to give you an idea.{ async createUser(@ApiRequest() req: req ) { // req.body is defined and validated } async getUser(@ApiRequest() req: req ) { // req.route.userId is defined and converted to number } async getUsers(@ApiRequest() req: req ) { // req.query.userId is defined (optionally) } }
2024.02.26 04:17 Leanador Using Expo Router, how to render different component if user already signed in?
root ⤷ (app) ⤷ (tabs) ⤷ home ⤷ index.tsx ⤷ (auth) ⤷ index.tsx _layout.tsxEssentially, (auth)/index.tsx is a page with sign-in and sign-up buttons, and (app) is where the remainder of the application is.
... return ()
... const [user, setUser] = useStateI use Supabase for my backend, and I believe the most guaranteed way of checking if a user is signed in with a valid session is with supabase.getUser(), which returns the user.(null); const router = useRouter(); const rootSegment = useSegments()[0]; useEffect(() => { // No user -> go to (auth) if (!user && rootSegment !== '(auth)') { router.replace('(auth)'); } // No user and in (auth) -> do nothing else if (!user) { return; } // User -> go to (app) else if (user && rootSegment !== '(app)') { router.replace('(app)/(tabs)/home'); } }, [user, rootSegment]) ...
2024.01.24 22:10 MysticAttack Midgame macro and carrying from the jungle
2023.10.31 15:02 DiegoDarkus Setting a cookie in nextjs 14 🥲
const fetchUser = async (): Promise=> { await getAccessToken("aaight"); // await axios.post( // "http://localhost:3000/api/set-cookie", // {}, // { // headers: { // Cookie: cookies().toString(), // }, // timeout: 5000, // } // ); const refreshToken = cookies().get("refresh-token"); // console.log("refresh token", refreshToken); if (!refreshToken) { return undefined; } console.log("\ncookie set\n", cookies().getAll()); // get user const getUser = await foodyApi.get >( "/users/me", { headers: { Cookie: cookies().toString(), }, timeout: 10000, } ); return { user: getUser.data.rsp.user, }; };
"use server"; import { cookies } from "next/headers"; export const getAccessToken = async (token: string) => { cookies().set("access-token", token, { path: "/", domain: "localhost", maxAge: 300, httpOnly: true, secure: false, }); };
import { cookies } from "next/headers"; export const POST = async (req: Request) => { // FIXME: check we got refresh token and api key console.log(cookies().get("access-token")); cookies().set("access-token", "we did it"); return Response.json( {}, { status: 200 } ); };
2023.10.08 05:26 GuyBelmont New Guy Belmont and Yuki Getsu character Bios
There here the new Character Bios all art has been done By the amazingly talented Morine / JoshYal.Art submitted by GuyBelmont to DraculasCastle [link] [comments] A Family History smeared in blood Guy's equipment The Vampire killer Excalibur whip the legendry holy whip that is bane of the night, passed down through the Belmont family for generations. the history of how the whip came to be has been mostly Lost to time, Only a hand full of people know. What is know however that the not only is the whip mind bendingly Holy powerful. It is also VERY versatile being able to make use of Magic stones, tips and Earth orbs, to power up the whip. Its also rumoured that the Gandolfi family though out the ages have hidden many upgrades For the whip in Mausoleums and other such places all over the world. to help further strengthen the Vampire Killer. Simons plate This legendry plate has seen many horrible nights but has helped vanquished the evil with the morning Sun. cyclone boots Legendry boots that have been said to give the wearer tremendous speed and jumping abilities. Seraph Shoulders This legendry relic is said be made from the wing of an arch angel giving the user the ability to sore to great Heights. Legend say that House Belmont was gifted with this Divine relic to better aid them in there Hunting of the night. Belmont Gauntlet A gauntlet that has been passed down through the clan for generations. it has been updated many times. it has mysterious powers. special techniques Holy Flame whip: when Guy charges up his Holy power, he is able to turn the Vampire Killer in to a Powerful holy flame whip, the higher guy's will power rises, the stronger the Holy flame whip becomes and the Longer it will last. Divine Rush: This attack combine speed and power. Guy strikes the whip with incredible speed and power so much that the whip becomes bluer of glowing white. faster and more powerful the whip gets the brighter it glows there is a also a purple hue that can bee seen around the whip. This technique not only creates a vortex that draws any unholy being in, but with each devastating strike creates a powerful sonic boom destroying both inside and out. any unholy being caught in this attack will be hit 999 times. Its one of Guys best know attack. He saw a technique in the Belmont Tome very much like this one, so he use it a base to fit his own Fighting style creating this powerful technique. Omnia Vanitas : "All is Vanity" an ancient technique was brought back with Leon Belmont from his trips around the world to become a better Monster hunter, This technique originates In japan. The Techniques Original name was Shikisokuzekū " All is nothing, nothing is all " This Powerful Technique make the user invulnerable and it lets the user Evade enemies and pass though solid objects like Monsters or fire walls leaving only your aura behind. it also allows the user to to cover a lot of ground using this Technique. However there is a down side not only is the Technique Very hard to master due to its complexity , but it also consumes a LOT of energy to use it, that goes double for prolonged usage. It was due to these complexity it got shelved in the hold, and forgotten to time, It was only found Buy Guy Belmont In 2994 when he was exploring the hold. and trying to absorb as much info on his family and there methods. is when he came across it. after spending mouths he finally managed to mastered it. Standard Sub weapons Like his ancestors he is armed with the standard sub weapons Axe Holy water Dagger cross stopwatch The Light In the Darkness. Yuki's equipment Alucard spear The legendry spear that was said to have been forged from the remains of the spear that beheaded Vlad Țepeș. The legend goes years later the Legendry hunter Alucard found the remains of the spear and sensed a great powerful aura emanating from it. So he decided to reforge it . By using his family's book of secret arts and then fusing it with the original Trident stake Of the Vampire Killer Whip, that was said to have been removed during a battle. And so with the reforging possessive completed The Alucard Spear was born, and Alucard had achieved in goal of creating a complement weapon to the holy whip Getsu clan Armour Family Armour that has been passed down for Generations . they say the armour was gift by the great dragon god. its believed that the armour was made out of his owns bones Hadou katana This spiritual blade which once swung, releases a wave of energy inflecting Incredible damage to Evil. This is the last Known Hadou Katana, and This treasured blade has been passed down throughout the clan for generations. being intrusted with the blade is Only true way to become head of the Getus clan. So One of the clan candidates who wants to become head of the clan. must Prove themselves worthy of the Blade. Once a candidates has proven themselves worthy. they are intrusted with the Hadou Katana and they are they now head of the Clan. The head is now able to enter all of the secret parts of the Getsu Clan Estate. Legend speaks that the other two other blades MAY still be out there. But this is often dismissed as just fairy tail or folklore. This spiritual blade is made of Both Light and darkness, A user is able to use one element at a time, turning it into a blade of light or darkness. BUT only 3 users in all of the clans History have been able to use both light and dark at the same time. the sister who went to Raging Demon Island to avenge her fallen older brothers and retrieve the Other Hadou Katanas and seal away Ryukotsuki. And Its this Brave women who started Yuki's Line. Kasmui Yuki's mother is also another who can use both Light and dark at the same time when using the blade. And finally Yuki too is able to use Both Light and darkness at the same time when she uses the blade. Iwa no Ken- rock sword. it said this blade is so powerful it can cut though almost anything, Given to Yuki by her mother. It was Yuki's first weapon before the Alucard Spear. Fuma's Greaves A great relic passed down though the Getsu clan they are made of bone, But no one is sure what sort if bone... Legends say they Increases running speed. special technique Dainendōha**: "**Great Will Aura": When Yuki Fuse the other 2 Hadou katana she is able to Unleash and unbelievably Powerful attack Known as the legendary Dainendōha. The power of dominance: the Getsu clan have the ability to absorb "Tamashii" "soul, spirit." from slan monsters, and by doing this it heals there wounds a little bit. However Yuki is able to Hold on to the soul of monsters she kills and then bring them out or use its powers. when Kasumi "Yuki's mother" first discovered Yuki was able to do this when she was at the age 7 Kasumi was not sure what to make of it. when she asked Yuki about Yuki gave a simple answer " I feel real sorry of em bein all cooped in there, so i like to let em out to breath once in a while. don't worry mama they won't go and do bad things any more they Promised." she smiled so earnestly and even though this technique comes from the darkest of places, she could sense no darkness coming from Yuki. So Kausmi knowing that sadly due to what and who Yuki was she would most likely be hunted down one day, so she wanted to train Yuki the best she could so she would be able to defend herself. told her to keep up with her training of this technique but do it in secret as no one would understand. And so the Yuki did and she now has Incredible control over it. Head chain of love and protection This head chain has the power to help protect from all forms of attack. when you hold it in your hand you can feel a warm feeling of love speared though your whole body. said to have been a gift from the progenitor of the Belmont clan to his betrothed. Given as a gift to Yuki from guy, as a way of signifying the bond between them. Getsu Clan regulation attack arms She is equipped with the same attack arms her clan is famous for The Defensive Drum The Curse Explosive The Shuriken The Defensive Ball The Devilish Top Thank you all for looking at these Bios Thank you everyone for all you're Support . |
2023.09.26 18:29 jezmilar Managed PostgreSQL with Next.js 13 (without an ORM) - optimal way to set it up? [code inside]
{data.email}
2023.09.20 12:39 kzovk State Management patterns between Server and Client components
Hi everyone. submitted by kzovk to nextjs [link] [comments] I want to clarify State Management patterns in the NextJS App router. It kinda feels like an obvious topic because there are literally no posts about it, so maybe I'm overthinking this. However, I've built a few small apps already, and each time I felt I was doing something wrong. ❗️Disclaimer: I am fairly new in the coding world, so I might be doing something fundamentally wrong. Please roast my approach and point out all the faults in my thinking. To simplify some stuff, let's say we have the following structure in the project. Let's assume we have only two types of data: User and UserProjects (that rely on UserID). https://preview.redd.it/dc477zgxxdpb1.jpg?width=2728&format=pjpg&auto=webp&s=ba5f1f410cbe9e2cdca38367844be581cb22b555 --- Now, I can see three options to get the correct data: Option 1: Server and drilling -- Data is fetched in the Layout and Page, then passed down to the components below. https://preview.redd.it/nks3xvn7ydpb1.jpg?width=2670&format=pjpg&auto=webp&s=eeeac6bd28a80b89f66f87e7bf2b5f6e92f6d53c Option 2: Server and drilling and react query -- User data:
Option 3: Server and react query -- Data is fetched directly in the components that need the data, using Server functions or React query - depending on the component type. https://preview.redd.it/hwav7j1nydpb1.jpg?width=2900&format=pjpg&auto=webp&s=c27f9bd3313e8538a0df8daf937befbadb204368 Now, we have to remember that I'm using React Query with Server actions - so the function for fetching this data is basically the same for client and server - it's just wrapped with React Query for the Client Components: https://preview.redd.it/1t2i8xfe0epb1.png?width=1266&format=png&auto=webp&s=f5c4b408d13622bb844e4ef55fc6d30e41d2f89e Now, I'm asking because I used the mix of 2 and 3 to find the best pattern. However, I do feel that using direct fetching in the server component makes my website slow. It feels like when I switch from subpage to subpage, the code for getUser and getUserProjects runs repeatedly, slowing everything down (because page loads only after the data is fetched). This problem does not occur in the ReactQuery, as the data is being refreshed in the background. I also don't understand whether NextJS calls the database every time to refresh the User, even though middleware already does it on every page change? Maybe I'm missing something. So, the questions are:
Here's the repo with example code: https://github.com/ky-zo/nextjs-app-router-state-mgmt Penny for your thoughts! Happy to learn from you. Cheers! |
2023.08.15 14:54 Mxfrj Project structure with database transactions
2023.08.14 23:08 alexyakunin Poor gRPC performance on test - help needed
System-wide settings: Thread pool settings: 48+ worker, 48+ I/O threads ByteSerializer.Default: MessagePack Starting server @ https://localhost:22444/ Client settings: Server URL: https://localhost:22444/ Test plan: 5.00s warmup, 4 x 5.00s runs Total worker count: 14400 Client concurrency: 120 Client count: 120 Stl.Rpc: Sum : 3.31M 3.21M 3.17M 3.24M -> 3.31M calls/s GetUser : 2.66M 2.66M 2.62M 2.64M -> 2.66M calls/s SayHello : 1.75M 1.72M 1.73M 1.72M -> 1.75M calls/s SignalR: Sum : 2.73M 2.72M 2.67M 2.71M -> 2.73M calls/s <-- compare this GetUser : 2.36M 2.31M 2.35M 2.35M -> 2.36M calls/s SayHello : 1.21M 1.20M 1.18M 1.20M -> 1.21M calls/s gRPC: Sum : 116.31K 129.65K 125.22K 125.28K -> 129.65K calls/s <-- with gRPC GetUser : 124.57K 125.63K 126.02K 122.40K -> 126.02K calls/s SayHello : 119.60K 123.33K 122.29K 120.76K -> 123.33K calls/s HTTP: Sum : 134.79K 143.42K 148.22K 143.03K -> 148.22K calls/s <-- moreover, gRPC ~= HttpClient GetUser : 141.18K 144.50K 139.19K 145.96K -> 145.96K calls/s SayHello : 129.53K 132.30K 128.41K 130.47K -> 132.30K calls/sTo run the test locally:
git clone git@github.com:servicetitan/Stl.Fusion.Samples.git cd Stl.Fusion.Samples dotnet run -c Release --project src/RpcBenchmark/RpcBenchmark.csproj -- testYou can also run its server & client on different machines like this:
dotnet run -c Release --project src/RpcBenchmark/RpcBenchmark.csproj -- server https://0.0.0.0:8888/ dotnet run -c Release --project src/RpcBenchmark/RpcBenchmark.csproj -- client https://serverIPOrHostName:8888/And two key options controlling the client are:
dotnet run -c Release --project src/RpcBenchmark/RpcBenchmark.csproj -- test -w 10000 -cc 1000 -b grpcSome notes on the test itself:
2023.05.17 18:05 Safe-Lander Can this approach be called "advanced" Authentication/Authorization?
user-controller.js ``` const brcypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const User = require("../model/User"); const signup = async (req, res, next) => { const { name, email, password } = req.body; let existingUser; try { existingUser = await User.findOne({ email: email }); } catch (error) { console.log("error: ", error); } if (existingUser) return res.status(400).json({ message: "User already exists" }); const hashedPassword = brcypt.hashSync(password); const user = new User({ name, email, password: hashedPassword, }); try { await user.save(); } catch (error) { console.log("error: ", error); } return res.status(201).json({ message: user }); }; const login = async (req, res, next) => { const { email, password } = req.body; let existingUser; try { existingUser = await User.findOne({ email: email }); } catch (error) { return new Error("error: ", err); } if (!existingUser) return res.status(400).json({ message: "User not found. Signup please" }); const isPasswordCorrect = brcypt.compareSync(password, existingUser.password); if (!isPasswordCorrect) return res.status(400).json({ message: "Invalid email or password" }); const token = jwt.sign({ id: existingUser._id }, process.env.JWT_SECRET_KEY, { expiresIn: "35s", }); if (req.cookies[`${existingUser._id}`]) { req.cookies[`${existingUser._id}`] = ""; } res.cookie(String(existingUser._id), token, { path: "/", expires: new Date(Date.now() + 1000 * 30), httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV, }); return res .status(200) .json({ message: "Successfully logged in.", user: existingUser, token }); }; const verifyToken = (req, res, next) => { const cookies = req.headers.cookie; // Gets cookies from header const token = cookies.split("=")[1]; if (!token) return res.status(404).json({ message: "Token not found" }); jwt.verify(String(token), process.env.JWT_SECRET_KEY, (error, user) => { if (error) return res.status(400).json({ message: "Invalid token" }); req.id = user.id; }); next(); }; const getUser = async (req, res, next) => { const userId = req.id; let user; try { user = await User.findById(userId, "-password"); // Send all the details of this User entry except the "password" field } catch (error) { return new Error(error); } if (!user) return res.status(404).json({ message: "User not found" }); return res.status(200).json({ user }); }; const refreshToken = (req, res, next) => { const cookies = req.headers.cookie; // Gets cookies from header const prevToken = cookies.split("=")[1]; if (!prevToken) return res.status(400).json({ message: "Couldn't find token" }); jwt.verify(String(prevToken), process.env.JWT_SECRET_KEY, (err, user) => { if (err) { console.log(err); return res.status(403).json({ message: "Authentication failed" }); } res.clearCookie(`${user.id}`); req.cookies[`${user.id}`] = ""; const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET_KEY, { expiresIn: "35s", }); res.cookie(String(user.id), token, { path: "/", expires: new Date(Date.now() + 1000 * 30), // 30 seconds httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV, }); req.id = user.id; next(); }); }; const logout = (req, res, next) => { const cookies = req.headers.cookie; // Gets cookies from header const prevToken = cookies.split("=")[1]; if (!prevToken) return res.status(400).json({ message: "Couldn't find token" }); jwt.verify(String(prevToken), process.env.JWT_SECRET_KEY, (err, user) => { if (err) { console.log(err); return res.status(403).json({ message: "Authentication failed" }); } res.clearCookie(`${user.id}`); req.cookies[`${user.id}`] = ""; return res.status(200).json({ message: "Logged out successfully" }); }); }; exports.signup = signup; exports.login = login; exports.verifyToken = verifyToken; exports.getUser = getUser; exports.refreshToken = refreshToken; exports.logout = logout; ```I've also added a limiter (it wasn't in the tutorial) to make it a bit more secure per ChatGPT's suggestion:
app.js ``` const express = require("express"); const mongoose = require("mongoose"); const router = require("./routes/user-routes"); const cookieParser = require("cookie-parser"); const cors = require("cors"); const rateLimit = require("express-rate-limit"); require("dotenv").config(); const app = express(); app.use(cors({ credentials: true, origin: "http://localhost:3000" })); app.use(cookieParser()); app.use(express.json()); // Apply rate limiting middleware const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Max requests per windowMs }); app.use(limiter); app.use("/api", router); mongoose .connect( `mongodb+srv://admin:${process.env.MONGODB_PASSWORD}@cluster0.nrlaqu0.mongodb.net/auth?retryWrites=true&w=majority` ) .then(() => { app.listen(5000); console.log("Database is connected! Listening to localhost 5000"); }) .catch((err) => console.log(err)); ```
2023.01.24 17:24 SeeDat_Ghai Anyone have a seller suggestion for this Air Max 97?
Hi all, looking for this particular air max 97 model submitted by SeeDat_Ghai to FashionReps [link] [comments] https://preview.redd.it/0bgixy67p0ea1.jpg?width=473&format=pjpg&auto=webp&s=b6990aff9560c5526e7659e3487b5d8b0d1550fa it is from this link Found something similar from lol2021 a previous post here but I think the link doesn't seem to be working anymore. Couldn't find it in his current air max inventory either. Saw people saying UMKAO's max's aren't the best. I tried putting GETU's taobao link (https://shop114840549.taobao.com/) from advice from this post into pandabuy but it kept giving me an error Tried putting in the image into pandabuy and there were fairly expensive reps ($70+) with a decent number of sales so just checking if there is a good and cheap option. Thx |
2023.01.22 08:36 RooCoder Redux API call with dynamic url paramter
getUser.js export default async (req, res) => { if (req.method === 'GET') { const username = ?????????? try { // How to get username??? const apiRes = await fetch(`${API_URL}/GetUseusername`, { method: 'GET', headers: { 'Accept': 'application/json', } }); const data = await apiRes.json(); if (apiRes.status === 200) { return res.status(200).json({ user: data }); } else { return res.status(apiRes.status).json({ error: data.error }); } } catch(err) { return res.status(500).json({ error: 'Something went wrong when retrieving user' }); } } else { // Error. Not a GET request. They tried POST or PUT etc. res.setHeader('Allow', ['GET']); return res.status(405).json({ error: `Method ${req.method} not allowed` }); } };My action:
// Get User Object export const load_user = () => async dispatch => { try { // Calls the above getUser.js const res = await fetch(`/api/getuser`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }); const data = await res.json(); if (res.status === 200) { dispatch({ type: LOAD_USER_SUCCESS, payload: data }); } else { dispatch({ type: LOAD_USER_FAIL }); } } catch(err) { dispatch({ type: LOAD_USER_FAIL }); } };
2022.12.09 04:49 bugman195 How to form render array from multiple APIs in React
// Here's the question 1, is it viable? const usersInfo = await Promise.all(promises) const usersMap = usersInfo.reduce((prev, curr) => { return { ...prev, [curr.data.userId]: curr.data, } }, {}) // Here's the question 2, is it the most efficient way? const finalList = rawComments.map(c => { return { ...c, userName: usersMap[c.userId].userName, userProfileUrl: usersMap[c.userId].userProfileUrl, } }) setRenderList(finalList)} catch(err) {} }
2022.12.02 16:26 TakenToTheRiver Status of All Software Updates is "Not Required" to 99% of Clients
2022.11.23 07:39 ErroneousLogik What is the best way to create a protected route with React Router v6.4 loaders?
const router = createBrowserRouter([ { path: "/", element:My associated loader function NewPostLoader is below, errorElement: , children: [ { path: "new", element: , loader: NewPostLoader, }]}])
export async function NewPostLoader() { //I want to check if user is authorised here using an api call and if not return redirect("/"); let ret = {}; ret['tags'] = await getTagsAll(); return ret }In the loader function above, my issue is not the api call but rather how I can get a token from the current App state to pass into the api call.
2022.09.23 19:19 witheredartery How to fix the issue of UseEffect not triggering on route change even after feeding in Params Object's property as dependency?
function App() { return (The route change to the user component happens in Home Component, I search for a github profile, a lift of profiles are displayed, I click on the visit profile button on the profile card, which Links me to User component); } } /> } /> } /> {/* ISSUE */} } />
import { Link } from 'react-router-dom' import PropTypes from 'prop-types' const UserItem = ({user: {login, avatar_url}}) => { return (My user Component where the function getUser needs to be triggered-> The function getUsers works fine as when i used it outside an useEffect, it did give me the right response from the fetch call inside.) } UserItem.propTypes = { user: PropTypes.object.isRequired, } export default UserItem;{login}
Visit Profile {/* TRIGGERING HERE!!!!!!!!!!! */}
import React, { useEffect, useContext } from 'react' import {FaCodepen, FaStore, FaUserFriends, FaUsers} from 'react-icons/fa' import { Link } from 'react-router-dom' import GithubContext from '../context/github/GithubContext' import { useParams } from 'react-router-dom' import Spinner from '../components/layout/Spinner' import RepoList from '../components/repos/RepoList' export const User = () => { const params = useParams() const { getUser, user, loading, getUserRepos, repos } = useContext(GithubContext) console.log("params", params, "login", params.login) // WORKS FINE useEffect ( () => { console.log("use-effect", getUser, "", params.login) getUser(params.login) getUserRepos(params.login) },[params.login]) // DOESNT TRIGGER WITH [] or [params.login] console.log( "user-check",user) // user object empty const { name, type, avatar_url, location, bio, blog, twitter_username, login, html_url, followers, following, public_repos, public_gists, hireable, } = user console.log("YES THIS PAGE") // Here I was checking whether page is being mounted and YES it is being mounted const websiteUrl = blog?.startsWith('http') ? blog : 'https://' + blog if(loading){ return} return (<> TYPICAL INFORMATION DISPLAY UI >) }
2022.09.19 15:56 TheLastSamuraiOf2019 Cannot access VM - Newbie
2022.09.19 13:31 p90fans CORS error: No 'Access-Control-Allow-Origin' header is present, while I already specified the origin in the server.
Hi all, I have read the doc from MDN, the post from SO, and this sub, however after many hours of struggling I want to get some idea here. submitted by p90fans to webdev [link] [comments] From what I understand, in order for my React frontend (in Vercel), to use API my Backend (in Heroku), I need to have my backend send a header of "Access-Control-Allow-Origin" to the frontend. Using this knowledge and ExpressJS with CORS library, the frontend successfully uses the API for the backend's database, however, it fails to use the API whose purpose is to receive user info from the server. In Developer Tool, the failed API just doesn't receive response headers that include Access-Control-Allow-Origin, and the console says origin (frontend domain) has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. To illustrate, the below screenshot is Developer Tools> Network, it is a 503 code. https://preview.redd.it/zwt79o46fto91.png?width=1959&format=png&auto=webp&s=9aa3ede4440e5b4696c01737d4f7bf9e96f99ea0 I suspect that it is because it involves some cookie credentials, and the MDN doc mentioned that credentials may affect CORS. Below is the frontend code (my apology that Inline Code does not work properly): const getUser = async () => { fetch(`${process.env.REACT_APP_BACKEND_URL}/auth/login/success`'/auth/login/success', { method: 'GET', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Access-Control-Allow-Credentials': true, 'Access-Control-Allow-Origin': 'https://xxx.vercel.app/' }, mode:'cors' })Below is the backend code const router = require('express').Router(); const cors = require('cors') router.get('/login/success', cors({ origin: [process.env.FRONTEND_URL, 'http://localhost:3000'], methods: 'GET, POST, PUT,DELETE', credentials: true, }), async (req, res) => { console.log('REQ.USER:LOGIN/SUCCESS', req.user);Any idea? : ( Update: I just wonder if I am not stating the actual problem, because in Network, there are two names both named "success", one is have no problem in cors , another one is not working, see below: https://preview.redd.it/29uqvbjshto91.png?width=2137&format=png&auto=webp&s=7e64c74921af5f3ca6fde1d729435e5038338977 https://preview.redd.it/d0w6vohthto91.png?width=1999&format=png&auto=webp&s=9dc388c6094a6cb9a77eaafdbb8082abb2a4026b |
2022.09.09 22:47 warpanomaly PUT request works in Postman but not a deno typescript file as a fetch request
I can do a put request just fine in Postman. submitted by warpanomaly to learnjavascript [link] [comments] https://preview.redd.it/kiublse1bwm91.png?width=1728&format=png&auto=webp&s=e90a40c91c3a11f228e13ae3534a71d291422d4d But when I try to do the same put request in a deno fresh app through a fetch command like this: async function sendSignature() { const signer = provider.getSigner(); const nonce = "asdf123492fd"; const signatureSigned = await signer.signMessage(nonce); const headers = new Headers({ 'Content-Type': 'application/json' }); const opts = { method: 'PUT', headers: headers, body: JSON.stringify({ key: props.singleUser, wallet_address: walletAddrs, signature: signatureSigned }) } console.log(opts.body); const rawPosts = await fetch('http://localhost:4000/users/kythis1', opts); console.log(rawPosts); }Btw all of the values are being populated in body. I can confirm that key, wallet_address, and signature are not null and are strings. It fails though... Here's what the browser's console looks like. https://preview.redd.it/hqn0scg4bwm91.png?width=1382&format=png&auto=webp&s=87bf4e8b250591f476c4bb61106aa57d41ed2a08 This is the entry point for the backend oak (deno's version of express) server. import { Application } from "https://deno.land/x/oak/mod.ts"; import { APP_HOST, APP_PORT } from "./config.js"; import router from "./routes.js"; import _404 from "./controllers/404.js"; import errorHandler from "./controllers/errorHandler.js"; import { oakCors } from "https://deno.land/x/cors/mod.ts"; const app = new Application(); app.use(oakCors()); // Enable CORS for All Routes app.use(errorHandler); app.use(router.routes()); app.use(router.allowedMethods()); app.use(_404); console.log(`Listening on port:${APP_PORT}...`); await app.listen(`${APP_HOST}:${APP_PORT}`);This is the function that is getting called by the put request: import User from "../db/database.js"; export default async ({ request, response }) => { if (!request.hasBody) { response.status = 400; response.body = { msg: "Invalid user data" }; return; } const body = request.body(); const { key, wallet_address, signature } = JSON.parse(await body.value); console.log(signature); if (!key) { response.status = 422; response.body = { msg: "Incorrect user data. Email and key are required" }; return; } const foundUser = await User.where('key', '=', key).first(); if (!foundUser) { response.status = 404; response.body = { msg: `User with key ${key} not found` }; return; } foundUser.wallet_address = wallet_address; foundUser.updated_at = new Date(); const updatedResp = await foundUser.update(); response.body = { msg: "User updated", updatedResp }; };Finally this is the backend routes: import { Router } from "https://deno.land/x/oak/mod.ts"; import getUsers from "./controllers/getUsers.js"; import getUserDetails from "./controllers/getUserDetails.js"; import createUser from "./controllers/createUser.js"; import updateUser from "./controllers/updateUser.js"; //import deleteUser from "./controllers/deleteUser.js"; const router = new Router(); router .get("/users", getUsers) .get("/users/:key", getUserDetails) .post("/users", createUser) .put("/users/:key", updateUser); //.delete("/users/:id", deleteUser); export default router;So why can I successfully call this function with a Postman put request, but I can't do a successful put request with fetch through a typescript file? |
2022.06.10 18:23 afoshx is this a good typescript codebase style?
const getUsers = async(req: Request, res:Response) => { const { title, description, city, } = req.body; const { id } = req.params; const doc = await doc.findById(id); if (!program) { return handleResponse(res, useWord("resourceNotFound", req.lang), 404); } doc.isPublished = isPublished; await doc.save(); }i see this part so often, is this really the right way tho ?
// lack of (unity) idk if that's good or not but ill explain more below #1 const getUsers = async(req: Request, res:Response) => { const { title, description, city, } = req.body; // router related const { id } = req.params; // router related // DB related const doc = await doc.findById(id); // db related if (!program) { return handleResponse(res, useWord("resourceNotFound", req.lang), 404); } // router related doc.isPublished = isPublished; // business logic await doc.save(); // db related }#1 - this means in the future, the logic related to getUser is bound to be repeated at some place, because now the business logic is bound to the express router, if i wanted to have the login feature anywhere else, ill either have to copy this code and repeat it somewhere else, or separate it into a function that's responsible for the business logic
const post = { title: "this is a posttitle", body: "this is a post body", isApproved: false, approvedBy: null, } function approvePost ( post, approvedBy ) { const sanitary = checkIfBodyHasBadWords(post.body); if(!sanitary) return false; post.isApproved = true; post.approvedBy = approvedBy; return true; } function checkIfBodyHasBadWords(body) { //complex sanitary computation }couldnt i have done it like this ?
const post = { title: "this is a posttitle", body: "this is a post body", isApproved: false, approvedBy: null, approvePost(approvedBy){ const sanitary = checkIfBodyHasBadWords(post.body); if(!sanitary) return false; this.isApproved = true; this.approvedBy = approvedBy; return true; } } post.approvePost(admin);i still actually have no frame of reference of what is "bad" and what is "good" typescript code, so typescript gods please have mercy on my ignorance, am trying to learn :)
2022.02.27 05:54 bottledpee Hi! i'm new to laravel and I'm trying to setup a new project for our company. I have a few questions regarding routing, type-hints, and route control groups and others. Please help!
Route::get('/users', 'App\Http\Controllers\UserController@getUsers');Syntax 2: *simple get but with a some kind of anonymous function
Route::get('/users', function () { //How do I specify that i'm trying to call the getUsers function here? cause this uses an anonymous function //because unlike syntax 1 and 4, the getUsers function is not specified in this syntax. });Syntax 3: *get request with type-hint/dependency injection as specified here: https://laravel.com/docs/9.x/routing#dependency-injection
Route::get('/users', function (GetUser $request) { //How do I call the getUsers function here? //because unlike syntax 1 and 4, the getUsers function is not specified in this syntax. });Syntax 4:
Route::get('/users', [UserController::class, 'getUsers']); //How do I use type hint here? Is it possible to specify here that //the getUsers function requires a GetUser FormRequest same way with syntax 3?Syntax 5: *I prefer to use this one because our project will be having a ton controllers but I don't know how to use type-hints/dependency injection here.
Route::controller(UserController::class)->group(function () { Route::get('/users', 'getUsers'); //how do I use type-hints here same as syntax 3. });As you can see I'm having trouble understanding the different syntaxes and how to write and use them properly.
2022.02.27 05:46 bottledpee Hi! i'm new to laravel and I have a few questions regarding routing, type-hints, and route control groups and others. Please help!
Route::get('/users', 'App\Http\Controllers\UserController@getUsers');Syntax 2: *simple get but with a some kind of anonymous function
Route::get('/users', function () { //How do I specify that i'm trying to call the getUsers function here? cause this uses an anonymous function //because unlike syntax 1 and 4, the getUsers function is not specified in this syntax. });Syntax 3: *get request with type-hint/dependency injection as specified here: https://laravel.com/docs/9.x/routing#dependency-injection
Route::get('/users', function (GetUser $request) { //How do I call the getUsers function here? //because unlike syntax 1 and 4, the getUsers function is not specified in this syntax. });Syntax 4:
Route::get('/users', [UserController::class, 'getUsers']); //How do I use type hint here? Is it possible to specify here that //the getUsers function requires a GetUser FormRequest same way with syntax 3?Syntax 5: *I prefer to use this one because our project will be having a ton controllers but I don't know how to use type-hints/dependency injection here.
Route::controller(UserController::class)->group(function () { Route::get('/users', 'getUsers'); //how do I use type-hints here same as syntax 3. });As you can see I'm having trouble understanding the different syntaxes.