0
import axios from 'axios';

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

server.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.
I write the client side in nextJS and when url calls, I use the 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.
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. But why is this and how can I solve this?

enter image description here

enter image description here

1
  • Shouldn't your request be to /api/email (with a leading /)? Commented Jun 2, 2021 at 0:29

1 Answer 1

0

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
The problem was 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 }));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.