Home > Software design >  How to connect Express JS to NotionAPI with POST and GET
How to connect Express JS to NotionAPI with POST and GET

Time:07-17

I am very new to backend so I am trying to implement a simple Notion form on a Typescript website. I was following this tutorial: enter image description here

Here is the code for my express server, app.js (exactly the same as the one in the tutorial):

const express = require('express')
const axios = require('axios')
const cors = require('cors')
const app = express()
const port = 3002

const secretKey = 'secret_[KEY REPLACED]'

const headers = {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${secretKey}`,
    'Notion-Version': '2022-02-22',
  }

  app.post('/704f58825cf841759f76733c5794e8aa', async (req, res) => {
    const { name, email } = req.body
    await axios({
      method: 'POST',
      url: 'https://api.notion.com/v1/pages',
      headers,
      data: {
        parent: { dat704f58825cf841759f76733c5794e8aaabase_id },
        properties: {
          "Name": { "title": [{ text: { content: name } }] },
          "Email": { "email": email }
        }
      }
    })
  })

  app.get('/:database_id', async (req, res) => {
    const { database_id } = req.params;
    const resp = await axios({
      method: 'GET',
      url: 'https://api.notion.com/v1/databases/'   database_id,
      headers
    });
    return res.json(resp.data)
  })
  
  app.use(cors())
  app.use(express.json())
  app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
  })

I am using ChakraUI for my front-end as well. This is the code for my main app, which is located outside of the server folder in the main app folder:

const database_id = '[KEY REPLACED]';

export default function ContactFormWithSocialButtons() {
  const { hasCopied, onCopy } = useClipboard('[email protected]');
  const [db, setDB] = useState({});
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');

  const onSubmit = (e) => {
    e.preventDefault();
    console.log(name);
    console.log(email);
    fetch('http://localhost:3002/'   database_id, {
      method: 'POST',
      body: JSON.stringify({ email: email, name: name }),
      headers: { "Content-Type": 'application/json' }
    });
  }

  useEffect(() => {
    fetch('http://localhost:3002/'   database_id).then(async (resp) => {
      setDB(await resp.json());
    });
  }, []);
  return (
    <Box
    bg={useColorModeValue('white', 'gray.700')}
    borderRadius="lg"
    p={8}
    color={useColorModeValue('gray.700', 'whiteAlpha.900')}
    shadow="base">
    <VStack spacing={5}>
      <form onSubmit={onSubmit}>
        <FormControl isRequired>
          <FormLabel>Name</FormLabel>
          <InputGroup>
            <InputLeftElement children={<BsPerson />} />
            <Input type="text" name="name" placeholder="Your Name"
            onChange={event => setName(event.currentTarget.value)} />
          </InputGroup>
        </FormControl>
        <FormControl isRequired>
          <FormLabel>Email</FormLabel>
          <InputGroup>
            <InputLeftElement children={<MdOutlineEmail />} />
            <Input
              type="email"
              name="email"
              placeholder="Your Email"
              onChange={event => setEmail(event.currentTarget.value)}
            />
          </InputGroup>
        </FormControl>
        <Button
          type="submit"
          colorScheme="blue"
          bg="blue.400"
          color="white"
          _hover={{
            bg: 'blue.500',
          }}>
          Send Message
        </Button>
      </form>
    </VStack>
  </Box>
  );
}

When I load the server with node app.js, everything works fine and the title of the database successfully loads onto the production page but as soon as I enter data to submit in the form I get this response:

enter image description here

I also get this error in console for my app.js page when I submit the form:

    const { name, email } = req.body
            ^

TypeError: Cannot destructure property 'name' of 'req.body' as it is undefined.

I will also mention that when I load the server with node app.js, the error Cannot GET / but all the data loads fine when I go to the API URL with the database ID in the URL (http://localhost:3002/[database ID]).

I have properly configured the Notion API integration and I have tried enabling Access-Control-Allow-Origin for Chrome, but I'm still facing these errors. If anyone can please help I would greatly appreciate it!!

CodePudding user response:

Before you can access req.body, you must use a body-parsing middleware like express.json:

app.post('/704f58825cf841759f76733c5794e8aa',
  express.json(),
  async (req, res) => {
    const { name, email } = req.body
    ...
  })
  • Related