简体   繁体   中英

Fetch request unable to get backend data due to Uncaught AxiosError - next.js and express.js

I'm trying to fetch some backend data on my Express.js backend which looks like this:

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") })

Every time the specific page loads I want it to fetch the {"data": ["data1", "data2", "data3"]} from the backend, I added a button that makes the same request for testing as well. Whenever I click the button and whenever the page loads I get this error:

在此处输入图像描述

I don't really understand why I'm getting this error, here is my next.js code:

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


export default function Product() {

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

  useEffect(() => {
    axios.get('/api').then(
      response => response.json()
    ).then(
      data => {
        setBackendData(data)
      }
    )
    console.log("ran")
  }, [])

  const test = () => {
    axios.get('/api').then(
      response => response.json()
    ).then(
      data => {
        setBackendData(data)
      }
    )
    console.log("test clicked")
  }


  return (
      <div style={styles.container}>
          <div style={styles.speechTitle}>Talk to us, tell us about your day...</div>
          <div style={styles.speechBox}>
            Test
          </div>
          <button onClick={console.log("start")}>
            Start
          </button>
          <button onClick={console.log("stop")}>Stop</button>
          <button onClick={console.log("reset")}>Reset</button>
          {(typeof backendData.data === 'undefined') ? (
            <p>Loading...</p>
          ) : (
            backendData.data.map((data, i) => (
              <p key={i}>{data}</p>
            ))
          )}
          <button onClick={() => test()}>asdasd</button>
      </div>

  );
}

I'm running this component called Product you see above in this file called product.js which is in my pages folder:

import React from 'react';
import { ThemeProvider } from 'theme-ui';
import { StickyProvider } from 'contexts/app/app.provider';
import theme from 'theme';
import SEO from 'components/seo';
import Layout from 'components/layout';
import Product from 'components/product-input'


export default function ProductPage() {
  return (
    <ThemeProvider theme={theme}>
        <StickyProvider>
          <Layout>
            <SEO title="Talkhappi" />
            <Product/>
          </Layout>
        </StickyProvider>
    </ThemeProvider>
  );
}

I am also getting a network error when I open up the network tab in developer tools:

在此处输入图像描述

I'm unsure how to fix this problem and retrieve the data I want to retrieve from my backend running at port 5000.

You seem to have to call your apis at port 5000 instead of 3000 you did.

  const baseURL = 'http://localhost:5000';

  const test = () => {
    axios.get(baseURL + '/api').then(
      response => response.json()
    ).then(
      data => {
        setBackendData(data)
      }
    )
    console.log("test clicked")
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM