【问题标题】:How to connect React front-end to NodeJS back-end API如何将 React 前端连接到 NodeJS 后端 API
【发布时间】:2020-11-29 23:00:52
【问题描述】:

拜托,我有一个 nodejs 产品 API,它显示待售产品列表和价格。它与邮递员配合得很好。现在,我想将它连接到我的反应前端。我的 nodejs 服务器在端口 http://localhost:8001 上运行,而我的 react 服务器在端口 http://localhost:3000 上运行。在我的 react 的 package.json 文件中,我在脚本对象下方添加了“proxy”:“http://localhost:8001/”。 但是当我从我的反应前端进行提取时,我收到错误“SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列的意外字符”。我试图将我的结果记录到控制台,但没有任何显示。 以下是我的代码。

React 中的 App.js 文件

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      response: "" 
    }
  }

   callAPI() {
    fetch('/products')
      .then(res => res.json())
      .then((result) => {        
        this.setState({ response: result })
      },
      (error) => console.log(error)
      );
  }

  componentDidMount() {
    this.callAPI();
  }

  render() {
    return(
      <>
        <h1>{this.state.response}</h1>
      </>
    )
  }
}

我在 react 中的 package.json 文件

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.2.2",
    "axios": "^0.21.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8001/",
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

我在 node.js 中的 app.js 文件

require('dotenv').config();
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');

const app = express();
app.use(cors());

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


// For people to access your API from other hosts
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Origin', 
    'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  );
  if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE');
    return res.status(200).json({});
  }
  next();
})

app.get('/products', (req, res, next) => {
  res.send({ "express": "Hello from express" });
});

app.use((req, res, next) => {
  const error = new Error('Not found');
  error.status = 404;
  next(error);
})

app.use((error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  })
})


module.exports = app;

【问题讨论】:

    标签: javascript node.js json reactjs express


    【解决方案1】:

    尝试从代理设置中删除最后一个斜线:

    "proxy": "http://localhost:8001"

    应该有帮助。

    【讨论】:

      【解决方案2】:

      是的,你是对的 - 斜线无关紧要。最后,我尝试运行您的代码,一切正常,但有一件事:

      在 App.js 文件中,渲染方法应更改为:

      render() {
          return(
            <>
              <h1>{JSON.stringify(this.state.response)}</h1>
            </>
          )
        }
      

      这只是我所做的修改。其余代码似乎没问题并且工作正常。 这是一个证明:screenshot,这里是 link 下载我的代码

      【讨论】:

        猜你喜欢
        • 2021-09-14
        • 1970-01-01
        • 2021-04-26
        • 2019-11-13
        • 2018-05-16
        • 1970-01-01
        • 2019-11-14
        • 1970-01-01
        • 2022-07-28
        相关资源
        最近更新 更多