I am trying to do a simple fetch request from a database hosted on a local server and also I am connected to mongodb in the backend, it seems like something is going wrong with my fetch method. I am getting Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR
and Uncaught (in promise) TypeError: Failed to fetch
function App() {
const [state, setState]= useState({
track: '',
artist:'',
album:'',
year: 1990
}
)
// const [token, setToken] = useState('');
useEffect(() => {
async function getData(){
const track = await fetch('https://localhost:3001/api/music')
.then(res => res.json());
console.log(track)
setState(track)
// console.log(res)
}
getData();
},[])
also this is my route&controller functions
router.get('/', musicCtrl.index)
controller:
function index(req, res){
Music.find({}, function(err, music){
res.status(200).json(music)
})
}
mongo connection
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const musicSchema = new Schema({
track: String,
artist: String,
album: String,
year: Number
}, {timestamps:true});
module.exports = mongoose.model('Music', musicSchema);
any help please ?!
You are using HTTPS in the fetch url.
Change
const track = await fetch('https://localhost:3001/api/music')
to
const track = await fetch('http://localhost:3001/api/music')
The getData function is also mixing await and .then. Change it to :-
async function getData(){
const track = await fetch('https://localhost:3001/api/music')
console.log(track.json())
setState(track.json())
}
Related
I am new to TRPC and have set up a custom hook in my NextJS app to make queries. This hook is sending out a query to generateRandomWorker but the response always returns a generic 500 error. I am completely stuck until I can figure out this issue.
The hook:
// filepath: src\utilities\hooks\useCreateRandomWorker.ts
type ReturnType = {
createWorker: () => Promise<Worker>,
isCreating: boolean,
}
const useCreateRandomWorker = (): ReturnType => {
const [isCreating, setIsCreating] = useState(false);
const createWorker = async (): Promise<Worker> => {
setIsCreating(true);
const randomWorker: CreateWorker = await client.generateRandomWorker.query(null);
const createdWorker: Worker = await client.createWorker.mutate(randomWorker);
setIsCreating(false);
return createdWorker;
}
return { createWorker, isCreating };
Here is the router. I know the WorkerService calls work because they are returning the proper values when passed into getServerSideProps which directly calls them. WorkerService.generateRandomWorker is synchronous, the others are async.
// filepath: src\server\routers\WorkerAPI.ts
export const WorkerRouter = router({
generateRandomWorker: procedure
.input(z.null()) // <---- I have tried completely omitting `.input` and with a `null` property
.output(PrismaWorkerCreateInputSchema)
.query(() => WorkerService.generateRandomWorker()),
getAllWorkers: procedure
.input(z.null())
.output(z.array(WorkerSchema))
.query(async () => await WorkerService.getAllWorkers()),
createWorker: procedure
.input(PrismaWorkerCreateInputSchema)
.output(WorkerSchema)
.mutation(async ({ input }) => await WorkerService.createWorker(input)),
});
The Next API listener is at filepath: src\pages\api\trpc\[trpc].ts
When the .input is omitted the request URL is /api/trpc/generateRandomWorker?batch=1&input={"0":{"json":null,"meta":{"values":["undefined"]}}} and returns a 500.
When the .input is z.null() the request URL is /api/trpc/generateRandomWorker?batch=1&input={"0":{"json":null}} and returns a 500.
Can anyone help on what I might be missing?
Additional Info
The client declaration.
// filepath: src\utilities\trpc.ts
export const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: `${getBaseUrl() + trpcUrl}`, // "http://localhost:3000/api/trpc"
fetch: async (input, init?) => {
const fetch = getFetch();
return fetch(input, {
...init,
credentials: "include",
})
}
}),
],
transformer: SuperJSON,
});
The init:
// filepath: src\server\trpc.ts
import SuperJSON from "superjson";
import { initTRPC } from "#trpc/server";
export const t = initTRPC.create({
transformer: SuperJSON,
});
export const { router, middleware, procedure, mergeRouters } = t;
Sorry I am not familiar with the vanilla client. But since you're in react you might be interested in some ways you can call a trpc procedure from anywhere while using the react client:
By using the context you can pretty much do anything from anywhere:
const client = trpc.useContext()
const onClick = async () => {
const data = await client.playlist.get.fetch({id})
}
For a known query, you can disable it at declaration and refetch it on demand
const {refetch} = trpc.playlist.get.useQuery({id}, {enabled: false})
const onClick = async () => {
const data = await refetch()
}
If your procedure is a mutation, it's trivial, so maybe you can turn your GET into a POST
const {mutateAsync: getMore} = trpc.playlist.more.useMutation()
const onClick = async () => {
const data = await getMore({id})
}
Answered.
Turns out I was missing the export for the API handler in api/trpc/[trpc].ts
I am making a test e-commerce sight to learn nextjs. I am trying to implement the checkout through stripe and I have it working if all of the information is static. when I make any of the information set to a variable it stops working and tells me that I am not passing any values into my variables. to test this I am making all of my data that needs to be passed, static data except for one which is when I get the error that I am not passing in information properly
obviously I am not sending the data to the api correctly. I think that my code looks just like the guides and docs so I am stuck. any help would be greatly appreciated.
here is the error message that I get:
"Missing required param: line_items[0][price_data][product_data][name]."
even if I change the state variable 'title' to a single value instead of an array, and in the updateState function settitle("title") I still get the same error
here is the front end code where I try to send the data to the api endpoint:
basket is an array of objects containing all of the products that the user has chosen.
const [id, setId] = useState([]);
const [price, setprice] = useState([]);
const [description, setdescription] = useState([]);
const [title, settitle] = useState([]);
const updateState = () => {
basket.forEach(element => {
setId([...id, element.id]);
setdescription([...description, element.description]);
setprice([...price, element.price]);
settitle([...title, basket.title]);
});
console.log(id);
console.log(description);
console.log(price);
console.log(title);
}
//send data to the api
const postData = async () => {
const response = await fetch("/api/checkout_sessions", {
method: "POST",
body: JSON.stringify(
id,
price,
description,
title,
),
});
return response.json();
};
return (
<form action="/api/checkout_sessions" method="POST">
<button
type="submit"
role="link"
className="button"
onClick={() => {
updateState;
postData;
}}
>
proceed to checkout
</button>
</form>
)}
here is the api code where I try to get that data and use it which is not working how I expect:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async function handler(req, res) {
// var priceVariable ='price_1MB8P4FqoomU2P4qrVmtxCvp';
if (req.method === 'POST') {
const items = req.body.id
const amount = req.body.price
const description = req.body.description
const title = req.body.title
try {
// Create Checkout Sessions from body params.
const session = await stripe.checkout.sessions.create({
// shipping_options: ["shr_1MBn0HFqoomU2P4qZk4vqOQ3"],
shipping_address_collection: {
allowed_countries: ["US", "CA", "GB"],
},
line_items:[{
price_data: {
unit_amount: 1000,
currency: 'usd',
product_data: {
name: title,
description: "description",
},
},
quantity: 1,
}],
mode: 'payment',
success_url: `${req.headers.origin}/?success=true`,
cancel_url: `${req.headers.origin}/?canceled=true`,
});
res.redirect(303, session.url);
} catch (err) {
res.status(err.statusCode || 500).json(err.message);
}
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
}
you can see in the line_items that everything is static except for the one variable that I am testing.
JSON.stringify expects an object (https://www.w3schools.com/js/js_json_stringify.asp)
const postData = async () => {
const response = await fetch("/api/checkout_sessions", {
method: "POST",
body: JSON.stringify({
id,
price,
description,
title,
}),
});
return response.json();
};
And on the api side you may have to parse the body before accessing any properties like so
const body = JSON.parse(req.body)
const title = body.title
(https://www.w3schools.com/Js/js_json_parse.asp)
It's unclear if the array/string mismatch is due to your testing changes, but you'll need to ensure a single string is supplied for name.
Your actual issue is likely here:
onClick={() => {
updateState;
postData;
}}
I'm surprised this is invoking the functions without (), but even if it were your postData() would start before the react state change happened.
I suspect if you initialized title with a value your endpoint would receive that.
const [title, setTitle] = useState("some default title");
You'll need to review how your application is tracking state here, and perhaps calculate that title and pass it through to the request alongside updating the state.
I am new to React & Axios, I'm trying to work my head around how to change the GET instance properties based on user inputs... If I am going about it the wrong way please direct me.
I want the selected dataFormat to pass to the params of the Axios.getData()
At the moment I can only get it to pass the object rather than its value.
Thanks in advance
Here is the code to fetch the data:
function App() {
let [responseData, setResponseData] = React.useState([]);
const [dataFormat, setDataFormat] = React.useState("json");
const fetchData = (e) => {
e.preventDefault();
console.log({dataFormat});
api
.getData(dataFormat)
.then((response) => {
console.log("Hello");
console.log(response);
setResponseData(response.data);
})
.catch((error) => {
console.log(error);
});
};
Here is the Axios instance
enter image description here
Here is the error I am receiving:
enter image description here
First you need to install the express library. Then, import cors and also use express.json() for parsing the json as shown below:
const express = require("express");
const app = express();
const cors = require("cors");
app.use(express.json());
app.use(cors());
function App() {
let [responseData, setResponseData] = React.useState([]);
const [dataFormat, setDataFormat] = React.useState("json");
const fetchData = (e) => {
e.preventDefault();
console.log({dataFormat});
api
.getData(dataFormat)
.then((response) => {
console.log("Hello");
console.log(response);
setResponseData(response.data);
})
.catch((error) => {
console.log(error);
});
};
I'm a beginner at both ReactJS and KoaJS.
I'm trying to send data from my React js form inputs to the server-side which was written with Koa.
Here is what I wrote to post data to the backend.
app.js
const FormContainer = () => {
const url = "http://localhost:3100/"
const [data,setData] = useState({
email:"",
firstname:"",
lastname:""
})
function submit(e){
e.preventDefault();
Axios.post(url, {
email: data.email,
firstname: data.firstname,
lastname: data.lastname
})
.then(res => {
console.log(res.data)
})
}
function handle(e){
const newData = {...data}
newData[e.target.id] = e.target.value
setData(newData)
console.log(newData);
}
Here is the server-side code
server.js
const Koa = require('koa');
const json = require('koa-json');
const KoaRouter = require('koa-router');
const bodyParser = require('koa-bodyparser');
const { default: App } = require('next/app');
const cors = require('#koa/cors');
const port = 3100
const server = new Koa();
const router = new KoaRouter();
server.use(json());
server.use(cors());
router.get('/', ctx => (ctx.body = {
}));
server.use(router.routes());
server.use(router.allowedMethods());
server.listen(port, () => console.log('Server Running'));
When I run the server, I keep getting this console error but I'm not sure what's wrong. Can someone help me? Thank you.
Error Image
i'm having a problem when i request GET to my api it returns me unauthenticated even though im logged in
my api code basically getSession returns null when im fetching on getServerSideProps but when im fetching on client side (useEffect it works perfectly)
i wanted a ssr that's why im trying to fetch in getServerside props
const handler = async (req, res) => {
if (req.method === "GET") {
const session = await getSession({ req });
if (!session) {
res.status(401).json({ message: "Not Authenticated" });
return;
}
const userId = session.user.id;
const client = await connectDb();
const db = client.db();
const tasks = await db
.collection("tasks")
.find({ user_id: userId })
.toArray();
res.status(200).json(tasks);
}
};
when i try to fetch on serverside it returns me message: "Not Authenticated"
export const getServerSideProps = async (context) => {
const res = await fetch(`http://localhost:3000/api/tasks`);
const data = await res.json();
return {
props: { data },
};
};
but when i fetch using useEffect (Client side) it works
useEffect(() => {
const fetchData = async () => {
const res = await fetch(`http://localhost:3000/api/tasks`);
const data = await res.json();
console.log(data);
};
fetchData();
}, []);
sorry i'm still new with this thank you in advance