#How can i check if a POST request contains a certain string?

468 messages · Page 1 of 1 (latest)

gritty heath
#

Hi guys! How can i check if a post request contains a certain string? [I'm using Next.js] Right now my api code is:

    if (session) {
        if (req.method !=='POST'){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }else if (req.contains !== session.user.email){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }
    } 

the "req.contains" doesn't exist, and i don't know how to check it, please help!

mighty ruin
#

console.log(req.body)

#

does that have what you're looking for?

gritty heath
#

wait.. i need to check if a POST request contains a specific string - the api works

gritty heath
mighty ruin
#

req.body will contain the data that you post to the api route

gritty heath
#

i know, the api works fine, i want to check if a POST request contains a certain string, for example, if a post request doesn't contains in a certain field the string "hi123" the server will respond with 405 status.

mighty ruin
#

No

#

req.body.yourField.includes("some string")

#

?

gritty heath
#

wait let me try

mighty ruin
#

I didn't realize you wanted the actual "includes" logic

#

because in the code snippet you posted above

#

req.contains is wrong, that's why I suggested you look for you field in req.body

gritty heath
#

ohh alright

#

so uhm.. it's not working

mighty ruin
#

debug further

#

add some console.logs

#

post your code here

gritty heath
#
import type { NextApiRequest, NextApiResponse } from "next"
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();


export default async (req:NextApiRequest, res:NextApiResponse) => {

    const session = await getSession({ req })

    if (session) {
        if (req.method !=='POST'){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }else if (req.body.user_id !== "numberz"){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }
    } 
    res.json({
        error: "Account not Found | Please Sign In.",
      })

      const notificationData = JSON.parse(req.body);
  
      const savedNotification = await prisma.notifications.create({
          data: notificationData
      })

};```
#

i've also tried with req.body.user_id.includes("test")

#

when i try to send a post request now there is this error

unborn sequoia
#

can you console.log(req.body.user_id)

gritty heath
#

but, why should i try console logging the user id? the user_id isn't the problem

#

the post method works, i just need to check if a field hasn't a specific string

sweet trench
#

i dont seem to understand your question, but i can help with little refractoring. The else if is not neccessary, as if and else if returns the same value in our situation. We could combine if and else if.

if (req.method !== "POST" || req.body..user_id !== "numberz") {
    return res.status(405).json({information: "ADD Method not allowed | Account found."})
}

i hope i helped you, please let me know if there was any errors.

sweet trench
sweet trench
gritty heath
#

yes, the body

gritty heath
sweet trench
#

can you try if the user_id is not undefined by console.log(user_id);

gritty heath
#

where can i console log it?

sweet trench
#

in your api code

gritty heath
#

oh okay i got it

sweet trench
#

inside the exported function.

gritty heath
#

like this??

#

done

sweet trench
#

the result will be available in the terminal ( the terminal where you ran npm run start)

gritty heath
#

oh

#

it's undefined

sweet trench
#

i have no prior experience with next-auth but i may try to help.

gritty heath
#

there is nothing related to next-auth here 😄

#

i just need to check the session.user.email that i already know how to

sweet trench
#

where did you make the request.

#

or are you using postman, etc...?

gritty heath
#

i'm making the request in another file

sweet trench
#

can you send that code of the file?

gritty heath
#

sure

#
import { useState } from "react";
import React from "react";
import { PrismaClient } from '@prisma/client';

import {useSession, signIn, signOut} from 'next-auth/react'


const prisma = new PrismaClient();

export const getServerSideProps = async () => {
  const data = await prisma.notifications.findMany();
  return {
    props: { games: data },
  };
};

async function registerNotification() {

  const response = await fetch('/api/companion', {
    method: 'POST',
    body: JSON.stringify({user_id: "numberzazzo", game_id: "testazzo"})
  })
  return await response.json();
}

const Home = ({ games }) => {

  function Accounter() {
    const { data: session } = useSession();
  
    if (session) {
      return (
        
        <div>
              <button onClick={registerNotification} user-id={session.user.email} className="bg-red-400 p-4 mb-4 rounded-xl">Subscribe</button>
              {games.map((game) => {
                return (
                <div key={game.notification_id}>
                  UID: <strong>{game.user_id}</strong> GID: {game.game_id}
                </div>
                )
              })
            }
        </div>
      )
    }else{
      return (
        
        <div>
          <h1><strong>NO SESSION, PLEASE LOG IN</strong></h1>
        </div>
      )
    }
  }


  return (
    <div className="min-h-screen ">
        <div className="min-h-screen bg-primary">
          <Header />
          <div>
              <Accounter></Accounter>
            </div>
          </div>
        </div>
  );
};

export default Home;
#

So, the code that makes the request is in registerNotification function

sweet trench
#

are you on vscode?

gritty heath
#

yes

sweet trench
#

there is a lightweight postman-like extension called Thunder Client, can you install it?

gritty heath
#

sure

#

i have now installed it

sweet trench
#

now press Ctrl + Shift + R or click the Thunder Client icon on your activity bar ( the one bar on the left )

gritty heath
#

done

sweet trench
#

i think its Ctrl + Shift + R, i dont remember quite well.

#

click on new request.

gritty heath
#

i did, now??

sweet trench
#

give it a name

gritty heath
#

uhm, how??

sweet trench
#

after clicking on new request they will ask for a name.

gritty heath
#

They're asking for an url

sweet trench
#

oh my bad.

gritty heath
#

the url should be the api url right??

sweet trench
#

yes

#

but with localhost

gritty heath
#

alright, i tried

sweet trench
#

change the GET to POST

gritty heath
#

the api can respond only to authenticated users

#

let me try

#

yea, this doesn't work

#

let me remove the authentication thing

sweet trench
#

change const session = await getSession({ req }) to const session = true for now.

gritty heath
#

done

sweet trench
#

and go to Body in Thunder Client

gritty heath
#

my bad, it works

sweet trench
#

{user_id: "numberzazzo", game_id: "testazzo"}

gritty heath
#

alright

sweet trench
#

whats the response?

gritty heath
#

it says "405 Method Not Allowed"

sweet trench
#

well here we prove its not a problem with api

#

oh i think i found the mistake

gritty heath
#

really? 🤨

sweet trench
#

fetch requires localhost

gritty heath
#

wait, wdym?

sweet trench
#
const response = await fetch('http://localhost:3000/api/companion', {
    method: 'POST',
    body: JSON.stringify({user_id: "numberzazzo", game_id: "testazzo"})
  })
#

axios allows you to use /api/companion but fetch doesn't

#

i forgot the http, try now.

gritty heath
#

i'm not using axios for the post request

#

the request works fine

#

alright, i've added the url on the fetch request

sweet trench
gritty heath
#

alright, i have axios installed as a library - but how do i use it?

sweet trench
#

i personally like and use axios.

#

its way easier

gritty heath
#

So.. should i use axios for this?

#

i don't know if something would change

sweet trench
#
import axios from 'axios';

// Usage
axios.post("/api/companion", {
user_id: "numberzazzo", game_id: "testazzo"
});```
gritty heath
#

is this right??

import { useState } from "react";
import React from "react";
import { PrismaClient } from '@prisma/client';
import axios from 'axios';


import {useSession, signIn, signOut} from 'next-auth/react'


const prisma = new PrismaClient();

export const getServerSideProps = async () => {
  const data = await prisma.notifications.findMany();
  return {
    props: { games: data },
  };
};

async function registerNotification() {

  axios.post("/api/companion", {
    user_id: "numberzazzo", game_id: "testazzo"
    });
  return await response.json();
}```
sweet trench
#

POST requests are axios.post. 1st parameter is the url, the second is an object of body

sweet trench
sweet trench
gritty heath
#

like this?


  const response = axios.post("/api/companion", {
    user_id: "numberzazzo", game_id: "testazzo"
    });
  return await response.json();
}
sweet trench
#

my bad i was mistaken

sweet trench
gritty heath
#

  const response= axios.post("/api/companion", {
    user_id: "numberzazzo", game_id: "testazzo"
    });
  return await response.json();
}```
sweet trench
#

there is no response.json

#

its already json

gritty heath
#

alright done

#

now it says that the Request failed with status code 405

sweet trench
#
async function registerNotification() {

  const response = await axios.post("/api/companion", {
    user_id: "numberzazzo", game_id: "testazzo"
    });
  return response;
}
gritty heath
sweet trench
#

405 is what you returned.

gritty heath
#

yes, but now the api denies all the requests regardless of by user_id

sweet trench
#

can you try again with ThunderClient

gritty heath
#

yes

sweet trench
gritty heath
sweet trench
#
    return res.status(405).json({information: "ADD Method not allowed | Account found."})
}```
#

change it to includes

gritty heath
#

done

sweet trench
gritty heath
#

Same error

sweet trench
#

using POST

gritty heath
#

oh lol

#

now i have another error

#

What's this?

#

i get this error in the console

sweet trench
#

but in HTML

#

thats HTML

#

req.body.user_id is undefined

gritty heath
#

i know

#

i said that before

sweet trench
#

so it doesnt work

gritty heath
#

alright wait

sweet trench
gritty heath
#

now it prints the post request correctly

sweet trench
#

great.

gritty heath
#

i've done it

#

now i get a 405 error

#

regardless by the request

sweet trench
gritty heath
#

yes

sweet trench
#

then change it to the one that worked.

gritty heath
#

So, now not even the code that was working before is now working

sweet trench
#

what?

gritty heath
#

and i'm getting this error:

sweet trench
#

you can use Ctrl + Z to undo btw.

gritty heath
#

i know

gritty heath
sweet trench
#

which os are you using?

gritty heath
#

windows

sweet trench
#

do npm upgrade

#

might work if its a dependency issue

sweet trench
#

but axios have bugs is rare

gritty heath
#

done, nothing changed

sweet trench
#

its an axios bug

sweet trench
gritty heath
#

yes

sweet trench
#

but the error seems to be fixed by axios

gritty heath
#
    at JSON.parse (<anonymous>)
    at __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(api)/./pages/api/companion/index.tsx:26:35)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Object.apiResolver (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\api-utils\node.js:366:9)
    at async DevServer.runApi (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\next-server.js:469:9)
    at async Object.fn (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\next-server.js:719:37)
    at async Router.execute (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\router.js:247:36)
    at async DevServer.run (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\base-server.js:346:29)
    at async DevServer.run (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\dev\next-dev-server.js:708:20)
    at async DevServer.handleRequest (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\base-server.js:284:20) {
  page: '/api/companion'
}
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:372:5)
    at NodeNextResponse.setHeader (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\base-http\node.js:61:19)
    at DevServer.renderError (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\base-server.js:978:17)
    at DevServer.renderError (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\next-server.js:827:22)
    at DevServer.run (D:\Progammi\ParaSoft\gamewatcher\node_modules\next\dist\server\dev\next-dev-server.js:714:35)```
sweet trench
#

this is a new error

#

can you send the code?

gritty heath
#
import { useState } from "react";
import React from "react";
import { PrismaClient } from '@prisma/client';
import axios from 'axios';


import {useSession, signIn, signOut} from 'next-auth/react'


const prisma = new PrismaClient();

export const getServerSideProps = async () => {
  const data = await prisma.notifications.findMany();
  return {
    props: { games: data },
  };
};

async function registerNotification() {

  const response = await axios.post("localhost/api/companion", {
    user_id: "numberz", game_id: "testazzo"
    });
  return response;
}

const Home = ({ games }) => {

  function Accounter() {
    const { data: session } = useSession();
  
    if (session) {
      return (
        
        <div>
              <button onClick={registerNotification} user-id={session.user.email} className="bg-red-400 p-4 mb-4 rounded-xl">Subscribe</button>
              {games.map((game) => {
                return (
                <div key={game.notification_id}>
                  UID: <strong>{game.user_id}</strong> GID: {game.game_id}
                </div>
                )
              })
            }
        </div>
      )
    }else{
      return (
        
        <div>
          <h1><strong>NO SESSION, PLEASE LOG IN</strong></h1>
        </div>
      )
    }
  }


  return (
    <div className="min-h-screen ">
        <div className="min-h-screen bg-primary">
          <Header />
          <div>
              <Accounter></Accounter>
            </div>
          </div>
        </div>
  );
};

export default Home;```
sweet trench
#

the problem was that you sent multiple requests

gritty heath
#

yes, maybe

#

alright now i get the same error

sweet trench
#

wait its the opposite, there were multiple response

#

can you try with ThunderClient

#

i think i found my mistake again

#

its res.data

#

return response.data

#

instead of return response

gritty heath
#

same error

sweet trench
#

check your url

gritty heath
#

oh right, my bad

#

yeaa same error again

sweet trench
#

404?

gritty heath
gritty heath
sweet trench
#
async function registerNotification() {

  const response = await axios.post("localhost/api/companion", {
    user_id: "numberz", game_id: "testazzo"
    });
  return response.data;
}
gritty heath
sweet trench
#

  const response = await axios.post("/api/companion", {
    user_id: "numberz", game_id: "testazzo"
    });
  return response.data;
}```
#

localhost was accidently there.

gritty heath
sweet trench
#

its okay to click multiple times btw, it was a mistake from my side.

sweet trench
gritty heath
#

yes i am

sweet trench
#

oh.

gritty heath
#

that's the correct url, i don't know what are all of these errors

sweet trench
#
async function registerNotification() {

  axios.post("/api/companion", {
    user_id: "numberzazzo", game_id: "testazzo"
    });
  return await response.json();
}```
does it work after changing back?
gritty heath
sweet trench
#

  const response = axios.post("/api/companion", {
    user_id: "numberzazzo", game_id: "testazzo"
    });
  return await response.json();
}```
gritty heath
#

TypeError: response.json is not a function

sweet trench
#

  const response = axios.post("/api/companion", {
    user_id: "numberzazzo", game_id: "testazzo"
    });
  return await response.json();
}``` i have no idea why i keep making these small mistakes
gritty heath
#

same error again

#

this is the same code as before

sweet trench
#

ahhhh

gritty heath
#

😂

sweet trench
#

  const response = await fetch('/api/companion', {
    method: 'POST',
    body: JSON.stringify({user_id: "numberzazzo", game_id: "testazzo"})
  })
  return await response.json();
}
#

its this at last

gritty heath
#

oohh now it works again 😎

sweet trench
#

you could remove axios

gritty heath
#

i know

#

i told ya

#

i didn't think that something would change with axios

sweet trench
#

better code.

gritty heath
#

instead of changing, it was making it worse

#

So, now the code for sending it works but the check doesn't

sweet trench
#

this is my first time encountering errors with axios.

gritty heath
gritty heath
sweet trench
#

check?

gritty heath
#

i need to check if a post request contains a certain string

#

yesss

sweet trench
#

oh

gritty heath
#

that's the main problemm

sweet trench
#

can you send the api code again?

gritty heath
#
import { getSession } from "next-auth/react"
import type { NextApiRequest, NextApiResponse } from "next"
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();

export default async (req:NextApiRequest, res:NextApiResponse) => {

    const session = await getSession({ req })

    if (session) {
        if (req.method !=='POST'){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }
    } 
    res.json({
        error: "Account not Found | Please Sign In.",
      })

      const notificationData = JSON.parse(req.body);

  
      const savedNotification = await prisma.notifications.create({
          data: notificationData
      })

};```
#

i've removed all the code that checks the post request

sweet trench
#
        if (req.method !=='POST' || req.body.user_id !== "numberz"){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }
}```
gritty heath
#

basically i now have the same file as we started

sweet trench
#

there was no check

gritty heath
#

i know

#

alright, now it rejects all the requests

#

even if the user_id is "numberz"

sweet trench
#

log user_id

#

is it undefined?

gritty heath
#

undefined

#

yes

sweet trench
#

make the request in ThunderClient

gritty heath
#

Done

#

It says Error 405 - and undefined on console

sweet trench
#

console.log(req.body)

gritty heath
sweet trench
#

console.log(req.body.user_id)

gritty heath
#

undefined

sweet trench
#

the result in short

gritty heath
sweet trench
#

does the user_id have some special character

gritty heath
#

no, it's just a text string

#

body: JSON.stringify({user_id: "numberz", game_id: "testazzo"})

#

this is what the button is sending

#

user_id is just a varchar

sweet trench
#
console.log(req.body[0].user_id)```
gritty heath
#

undefined

#

oh

#

new error

#

and now the response is bugged

sweet trench
#

i expected that

#
console.log(req.body);
console.log(req.body.user_id)```
gritty heath
#
undefined```
sweet trench
#

what the hell

gritty heath
#

yess i know this is pretty strange

sweet trench
#

console.log(req.body.user_id)

#

i doubt there maybe any special characters

gritty heath
#

undefined

#

maybe we need to convert that in json or something like that

sweet trench
#

how could this happen

gritty heath
#

i don't know

sweet trench
#

its already JSON

gritty heath
#

this is very strange

#

oh

sweet trench
#

console.log(req.body.game_id)

gritty heath
#

wait what??

sweet trench
gritty heath
#

yeaaa but i think i should change this in the database table, right?

sweet trench
#

its fine

#

variables can contain underscores

sweet trench
gritty heath
#

undefined

#

this is frustrating 😄

sweet trench
#

console.log(req.body[0])

sweet trench
gritty heath
#

wrong

#

it just printed "{"

inland badge
#

can you console.log req.query ?

gritty heath
inland badge
#

What was the POST request url?

sweet trench
#

click Body in ThunderClient

gritty heath
#

I Think it's http://localhost:3000/api/companion?user_id=numberz&game_id=ciao124

sweet trench
#

and then ```js
{
"user_id": "numberz",
"game_id": "ciao123"
}

gritty heath
#

wait.. wdym?

sweet trench
#

what you did was using Query. change the url back to http://localhost:3000/api/companion and click Body next to Auth and Tests

sweet trench
gritty heath
#

alright with the query, the console.log says this:

#

without it, it says "{}"

sweet trench
#

remove both Query Parameters

#

it does not have any use.

#

console.log(req.body.user_id)

gritty heath
#

alright, now it says numberz

#

POST http://localhost:3000/api/companion 405 (Method Not Allowed)

sweet trench
#

what am i sending.

#
        if (req.method !=='POST' || req.body.user_id !== "numberz"){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }
}```
gritty heath
#

POST http://localhost:3000/api/companion 405 (Method Not Allowed)

#

Prolly cause you're sending your values as parameters but checking the body

#

Resolved it yet?

#

Should be something like this

#
const { user_id, game_id } = req.query
#

so, from the html button it says "undefined" - but if i make the request with the postman plugin it prints the "numberz" string but now there is this problem that i don't get if i put anything different between "numberz":

gritty heath
sweet trench
#

add http://localhost:3000 in the fetch request

#

@gritty heath

gritty heath
gritty heath
#

add it before if (session)

#

then replace req.body.user_id !== "numberz"

#

with user_id !== "numberz"

sweet trench
#
async function registerNotification() {

  const response = await fetch('http://localhost:3000/api/companion', {
    method: 'POST',
    body: JSON.stringify({user_id: "numberzazzo", game_id: "testazzo"})
  })
  return await response.json();
}
gritty heath
#

You have to understand two fundamental things here.

domain.com/x=1&y=2, x and y here are HTTP parameters. You can get their values through req.query

But if you send the values in the body, you can extract their values through req.body

sweet trench
#

its fully implemented through req.body

gritty heath
sweet trench
#

changing to query might require more time

gritty heath
#

Send it through that if you want to receive it through req.body

#

They're conveniently named query and body.

#

Query tab -> req.query
Body tab -> req.body

It can't work any other way.

gritty heath
#

Here, to better show the difference

#
// Sending it as payload, access through req.body
fetch('http://localhost:3000/api/companion', {
    method: 'POST',
    body: JSON.stringify({user_id: "numberzazzo", game_id: "testazzo"})
  })
// This is what you are doing in that postman clone
// Sending it as params, access through req.query.
fetch('http://localhost:3000/api/companion/user_id=numberzazzo&game_id=testazzo', method: 'POST'})
#

is there something wrong here?

gritty heath
gritty heath
#

Should be { method: "POST" }

gritty heath
gritty heath
#

Share the handler code maybe?

#

For the endpoint

#

wdym?

#

Try removing the / after companion

#

replace it with ?

#

alright now it says "Undefined" And it gives this error:

#

Can you show your server's code?

#

For the handler, the one that processes the request

#
import type { NextApiRequest, NextApiResponse } from "next"
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();

export default async (req:NextApiRequest, res:NextApiResponse) => {

    console.log(req.body.user_id)

    const session = true

    if (session) {
        if (req.method !=='POST' || req.body.user_id !== "numberz"){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }
    } 
    res.json({
        error: "Account not Found | Please Sign In.",
      })

      const notificationData = JSON.parse(req.body);
  
      const savedNotification = await prisma.notifications.create({
          data: notificationData
      })

};```
#
import { getSession } from "next-auth/react"
import type { NextApiRequest, NextApiResponse } from "next"
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();

export default async (req:NextApiRequest, res:NextApiResponse) => {

    const { user_id, game_id } = req.query

    const session = true

    if (session) {
        if (req.method !=='POST' || user_id !== "numberz"){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }
    } 
    res.json({
        error: "Account not Found | Please Sign In.",
      })

      const notificationData = JSON.parse(req.body);
  
      const savedNotification = await prisma.notifications.create({
          data: notificationData
      })

};```
#

Do something after checking if the method and userid is valid

#

You aren't doing anything

#
import { getSession } from "next-auth/react"
import type { NextApiRequest, NextApiResponse } from "next"
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();

export default async (req:NextApiRequest, res:NextApiResponse) => {

    const { user_id, game_id } = req.query

    const session = true

    if (session) {
        if (req.method !=='POST' || user_id !== "numberz"){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }

        // Do something here, return a success message or something
    } 
    res.json({
        error: "Account not Found | Please Sign In.",
      })

      const notificationData = JSON.parse(req.body);
  
      const savedNotification = await prisma.notifications.create({
          data: notificationData
      })

};
#

Oh wait, I see. Try removing the lines starting from notificationData.

#

Done

#

Now what should i do?? if i click the button nothing happens now

#
import { getSession } from "next-auth/react"
import type { NextApiRequest, NextApiResponse } from "next"
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();

export default async (req:NextApiRequest, res:NextApiResponse) => {

    const { user_id, game_id } = req.query

    const session = true

    if (session) {
        if (req.method !=='POST'){
            res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        } else if (user_id !== "numberz") {
            res.status(405).json({error: "Account not Found | Please Sign In."})
        } else {
            res.status(200).json({information: `Account Found | Method Allowed.`})
        }
        res.end()
    } 

    // Remove this for now
      // const notificationData = JSON.parse(req.body);
      //
      // const savedNotification = await prisma.notifications.create({
      //     data: notificationData
      // })
};
gritty heath
#

That's pretty much it I think

#

I have 0 idea what you're doing on the line I've commented so I can't help with that.

#

Now my code is like this:

import type { NextApiRequest, NextApiResponse } from "next"
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();

export default async (req:NextApiRequest, res:NextApiResponse) => {

    const { user_id, game_id } = req.query

    const session = true

    if (session) {
        if (req.method !=='POST' || user_id !== "numberz"){
            return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
        }

        console.log("data added!")

    } 
    res.json({
        error: "Account not Found | Please Sign In.",
      })



};```
gritty heath
#

You're still not doing anything on success there.

#

You can refactor that to reduce the nested ifs but that's up to you now.

#

nothing of this is working right now - i need to add data to my database and if the user_id field is different from "test123" i send an 405 status. this isn't working

#

now the button isn't adding any data

#

No data is being added right now in the database

gritty heath
#

yeah, but what's the meaning of it now?

#

Add it back?

#
import { getSession } from "next-auth/react"
import type { NextApiRequest, NextApiResponse } from "next"
import { PrismaClient } from '@prisma/client';


const prisma = new PrismaClient();

export default async (req:NextApiRequest, res:NextApiResponse) => {

    const { user_id, game_id } = req.query

    const session = true

    if (!session) {
        const notificationData = JSON.parse(req.body);
        await prisma.notifications.create({ data: notificationData })
        res.status(401).end()
    } 

    if (req.method !=='POST'){
        res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
    } else if (user_id !== "numberz") {
        res.status(405).json({error: "Account not Found | Please Sign In."})
    } else {
        res.status(200).json({information: `Account Found | Method Allowed.`})
    }
    res.end()
};
#

At this point, you should be paying me as a consultant haha

gritty heath
#

Set session = false and it should write some data now

#

500 internal server error

#

well, we're trying to fix this for everyone, i don't think this would be useful only for my purposes 😅

#

if there is a fix to this, i'll recommend the staff to add it to the docs or something like that

#

because i still can't find this specific informations in the nextjs docs

#

I'm 90% certain its being caused by prisma

#
export default async (req:NextApiRequest, res:NextApiResponse) => {
    const { user_id, game_id } = req.query

    const session = false

    if (!session) {
        // const notificationData = JSON.parse(req.body);
        // await prisma.notifications.create({ data: notificationData })
        console.log('No session')
        res.status(401).json({ error: 'Unauthorized' })
        res.end()
    }

    if (req.method !=='POST'){
        res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
    } else if (user_id !== "numberz") {
        res.status(405).json({error: "Account not Found | Please Sign In."})
    } else {
        res.status(200).json({information: `Account Found | Method Allowed.`})
    }
    res.end()
};
#

Try that

#

Then run this on the command line

#
curl -X POST "http://localhost:3000/api/companion?user_id=numberz&game_id=testazzo"
#

Check your server's console logs. If it shows "No session", then everything works except for prisma.

#

it prints "No session" as expected but there is a bug maybe?

#

Um, show you code? Seems like you're modifying res even after it was sent

gritty heath
#

Don't do anything after the response is sent

#
import React from "react";
import { PrismaClient } from '@prisma/client';


import {useSession, signIn, signOut} from 'next-auth/react'


const prisma = new PrismaClient();

export const getServerSideProps = async () => {
  const data = await prisma.notifications.findMany();
  return {
    props: { games: data },
  };  
};

async function registerNotification() {

  const response = await fetch('http://localhost:3000/api/companion?user_id=numberz&game_id=testazzo', {method: 'POST'})
  return await response.json();
}

const Home = ({ games }) => {

  function Accounter() {
    const { data: session } = useSession();
  
    if (session) {
      return (
        
        <div>
              <button onClick={registerNotification} user-id={session.user.email} className="bg-red-400 p-4 mb-4 rounded-xl">Subscribe</button>
              {games.map((game) => {
                return (
                <div key={game.notification_id}>
                  UID: <strong>{game.user_id}</strong> GID: {game.game_id}
                </div>
                )
              })
            }
        </div>
      )
    }else{
      return (
        
        <div>
          <h1><strong>NO SESSION, PLEASE LOG IN</strong></h1>
        </div>
      )
    }
  }


  return (
    <div className="min-h-screen ">
        <div className="min-h-screen bg-primary">
          <Header />
          <div>
              <Accounter></Accounter>
            </div>
          </div>
        </div>
  );
};

export default Home;
gritty heath
#
  const data = await prisma.notifications.findMany();
  return {
    props: { games: data },
  };  
};

async function registerNotification() {

  const response = await fetch('http://localhost:3000/api/companion?user_id=numberz&game_id=testazzo', {method: 'POST'})
  return await response.json();
}```
gritty heath
#

wait, for what?

gritty heath
#

The export default async (req:NextApiRequest, res:NextApiResponse) one

#
    const { user_id, game_id } = req.query

    const session = false

    if (!session) {
        // const notificationData = JSON.parse(req.body);
        // await prisma.notifications.create({ data: notificationData })
        console.log('No session')
        res.status(401).json({ error: 'Unauthorized' })
        res.end()
    }

    if (req.method !=='POST'){
        res.status(405).json({information: `ADD Method Not Allowed | Account Found.`})
    } else if (user_id !== "numberz") {
        res.status(405).json({error: "Account not Found | Please Sign In."})
    } else {
        res.status(200).json({information: `Account Found | Method Allowed.`})
    }
    res.end()
};```
gritty heath
#

Can you do this

#
if (!session) {
        // const notificationData = JSON.parse(req.body);
        // await prisma.notifications.create({ data: notificationData })
        console.log('No session')
        res.status(401).json({ error: 'Unauthorized' })
        res.end()
        return
    }
#

alright, now it only says "No session"

#

So now it works, try this now

#
export default async (req:NextApiRequest, res:NextApiResponse) => {
    const { user_id, game_id } = req.query

    const session = false

    if (!session) {
        await prisma.notifications.create({ data: {user_id: user_id, game_id: game_id }})
        return res.status(401).json({ error: 'Unauthorized' }).end()
    }

    if (req.method !=='POST'){
        return res.status(405).json({information: `ADD Method Not Allowed | Account Found.`}).end()
    } else if (user_id !== "numberz") {
        return res.status(405).json({error: "Account not Found | Please Sign In."}).end()
    } else {
        return res.status(200).json({information: `Account Found | Method Allowed.`}).end()
    }
};
#

I've updated the snippet, try again

#

yup, add another curly

#

401 unauthorized

#

Then its working

#

401 means it has no session.

#

WAIT

#

A notification should be added

#

YES

#

THE NOTIFICATION IS NOW ADDED

#

Now, you have another problem

#

Clarify if you want those values to be sent as params or in the body

#

alright wait, wdym?

#

what's the difference between them?

#
const { user_id, game_id } = req.query // Choose this is through params
const { user_id, game_id } = req.body // Choose this if through body
#

oh i see

#

Params are those additional values in the url ?param1=a&param2

#

You can send the data through the body, url will be the same without the param

#

ohh i see

#

params are alright

#

so, now there is a little problem

#

when data gets added, i have this error:

#

just remove end()

#

everywhere

#

Honestly, I have no idea what its for

#

its probably something you add if you dont send back a message

#
res.status(405).end()
res.status(405).json(...)
#

Cant be both I guess

#

DAMN YOU'RE A GENIUS MY BROTHERRR

#

I know that this is pretty easy for you, but for me it means very much, thank you so much for your time, god bless you!!

#

no worries

gritty heath
#

@sweet trench @unborn sequoia @mighty ruin @gritty heath Thank you guys!!

gritty heath
#

Hi.. what's this problem now??

#

i was going to close this thread 😅

gritty heath
#

@gritty heath

#

Convert game_id to a list.

#

🤨

#

All values returned by req.query are string

#

alright, how can i convert it??

#

i'm a noob with this sorry 😂

#

I'll say this with good intent to help you grow as a dev. I can send you the code but I won't, with the hope that you'd figure it out yourself. I'd suggest you to refresh on fundamentals.

Your original problem was essentially revolving around the logic flow of your code. You were executing your statements in an incorrect order.

On your second problem, your IDE is straight up telling you "Hey man, these are two different data types". You should have the intuition to try to match up the data type as required. To do that, you'll have to execute 2 functions at most, which I believe you can figure out.

#

Uhhh i think i fixed it

#

is this right?

#

now it doesn't give any error

#

i just added the | string[]

gritty heath