简体   繁体   English

axios 不通过 http-proxy-middleware 向服务器发送 post 请求

[英]axios does not send post request to server via http-proxy-middleware

import axios from 'axios';

axios
  .post('api/email', { id: 1 })
  .then((res) => {
     return res.data;
  })

server.js服务器.js

const express = require('express');
const next = require('next');
const { createProxyMiddleware } = require('http-proxy-middleware');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';

const app = next({ dev });
const handle = app.getRequestHandler();

const apiPaths = {
  '/api': {
    target: 'http://localhost:8080/',
    pathRewrite: {
      '^/api': '/api',
    },
    changeOrigin: true,
  },
};

const isDevelopment = process.env.NODE_ENV !== 'production';

app
  .prepare()
  .then(() => {
    const server = express();

    server.use(express.json());
    server.use(express.urlencoded({ extended: false }));
    if (isDevelopment) {
      console.log('ok');
      server.use('/api', createProxyMiddleware(apiPaths['/api']));
    }

    server.all('*', (req, res) => {
      return handle(req, res);
    });

    server.listen(port, (err) => {
      if (err) throw err;
      console.log('> Ready on http://localhost:' + port);
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

My server is located at localhost: 8080.我的服务器位于本地主机:8080。
I write the client side in nextJS and when url calls, I use the http-proxy-middleware package.我在 nextJS 中编写客户端,当 url 调用时,我使用 http-proxy-middleware package。 That is, all my requests that contain / api / will be redirected from localhost: 3000 to localhost: 8080. axios does not send post request, get is fine.也就是说,我所有包含/api/的请求都会从localhost:3000重定向到localhost:8080。axios不发送post请求,get就好了。
When viewing the Network tab in a developer mode browser, it shows the request headers itself, but without the method.在开发人员模式浏览器中查看“网络”选项卡时,它会显示请求标头本身,但没有方法。 The timing tab displays Caution request is not finished yet.计时选项卡显示警告请求尚未完成。

UPD: I just tried sending via fetch, the result is the same, but I also removed Content-Type: 'application / json' and fetch worked for me. UPD:我刚刚尝试通过 fetch 发送,结果是一样的,但我也删除了 Content-Type: 'application / json' 并且 fetch 对我有用。 But why is this and how can I solve this?但是为什么会这样,我该如何解决呢?

在此处输入图像描述

在此处输入图像描述

I was able to solve my problem.我能够解决我的问题。 Solutions found here: https://github.com/chimurai/http-proxy-middleware/issues/40 , socket hang up error with nodejs在这里找到的解决方案: https://github.com/chimurai/http-proxy-middleware/issues/40,nodejs套接字挂断错误
The problem was server.js问题是 server.js
Here is the corrected code这是更正后的代码

if (isDevelopment) {
  console.log('ok');
  server.use('/api', createProxyMiddleware(apiPaths['/api']));
}
server.use(express.json());
server.use(express.urlencoded({ extended: false }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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