首页 > 解决方案 > React 代理在 url 中创建双“帖子”

问题描述

我正在尝试对后端进行代理,它适用于“api/posts”,但是当我想要“api/posts/:id/blaa ...”时,它会发送类似“posts/api/posts/:id”的请求。 ...'。

这是后端控制台中的日志:

GET /api/posts 200 877.196 ms - 28709
GET /posts/api/posts/5b249d69b965e2776dbcf65e 404 0.566 ms - 179
GET /posts/api/comments 404 0.500 ms - 157

这是来自前端的 package.json:

{
  "name": "reactfront",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "email-validator": "^2.0.4",
    "history": "^4.7.2",
    "node-sass-chokidar": "^1.3.0",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-loading": "^2.0.2",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.3.1",
    "react-scripts": "1.1.4",
    "redux": "^4.0.0",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.3.0",
    "reselect": "^3.0.1",
    "semantic-ui-css": "^2.3.2",
    "semantic-ui-react": "^0.81.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:5000/"
}

以下是获取请求的样子:

const API_URL = "api";

export const getPosts = () => dispatch => {
  dispatch({
    type: GET_POSTS
  });
  fetch(API_URL + "/posts", {
    method: "GET",
    headers: { 

标签: javascriptreactjsexpressproxy

解决方案


如我所见,您的 URLfetch(API_URL + "/posts", {是相对的(它是“api/posts”,也许它应该是绝对的(“/api/posts”)。


推荐阅读