Having trouble setting up express backend for next.js

Viewed 24

I'm trying to set up an express backend in a separate directory from where all my next.js stuff is. I labeled my enxt.js folder client and my backend with the node and express server. I'm trying to fetch some data using axios from the backend but it's not happening and I don't know why. This is my backend code:

const express = require('express')
const app = express()

app.get("/api", (req, res) => {
    res.json({"data": ["data1", "data2", "data3"]})
})

app.listen(5000, () => { console.log("Server started on port 5000, hi") })

This is my next.js frontend code which is performing the fetch request:

import React, { Component, useEffect, useState } from 'react';
import axios from 'axios';

// Speech to text recognition modules
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition'


const Product = () => {
  // Import variables from speech recognition hook
  const {
    transcript,
    listening,
    resetTranscript,
    browserSupportsSpeechRecognition,
    isMicrophoneAvailable
  } = useSpeechRecognition();

  const [backendData, setBackendData] = useState([{}])

  useEffect(() => {
    axios.get('http://localhost:5000/api').then(
      response => response.json()
    ).then(
      data => {
        setBackendData(data)
      }
    )
  }, [])

  // Handle browser support error
  if (!browserSupportsSpeechRecognition) {
    return <span>Browser doesn't support speech recognition.</span>;
  }

  // Handling microphone setting turned off
  if (!isMicrophoneAvailable) {
    return <span style={styles.container}><strong>Enable your microphone to use the web app!</strong></span>
  }

  return (
      <div style={styles.container}>
          <div style={styles.speechTitle}>Talk to us, tell us about your day...</div>
          <div style={styles.speechBox}>
            {transcript}
          </div>
          <p>Microphone: {listening ? 'on' : 'off'}</p>
          <button onClick={() => SpeechRecognition.startListening({
            continuous: true,
            language: 'en-US'
          })}>
            Start
          </button>
          <button onClick={SpeechRecognition.stopListening}>Stop</button>
          <button onClick={resetTranscript}>Reset</button>
          {(typeof backendData.data === 'undefined') ? (
            <p>Loading...</p>
          ) : (
            backendData.data.map((data, i) => (
              <p key={i}>{data}</p>
            ))
          )}
      </div>

  );
}

export default Product

I'm unable to see any fetch requests in the Network section of the developer tools as well. Does anyone know what I can do to make this work?

0 Answers
Related