Axios获取请求响应400错误请求

时间:2019-07-10 07:28:24

标签: node.js reactjs express get axios

我正在从我的React前端(在端口8080上)向我的Express后端(仅在端口5000上的同一地址上)发送axios get请求。该请求是公共请求,没有数据只是发送获取请求以返回json网络令牌。

这是我公司的Web应用程序,因此我必须限制我可以共享的内容。我正在使用PM2在centos服务器上服务器前端和后端。两者都在相同的IP地址前端(从8080后端到5000)上运行。在localhost中都可以正常工作,但是当我在服务器上运行webpack build和host时,会发生错误的请求。

反应前端

if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = 'http://ipAddressOfBackend:5000//';
}

axios.get('/api/user/generateToken')
  .then(payload => {
    // ----- Set auth and store token -----
  }
  .catch(err) => {
    console.log(err.response);
  };

Express / Node后端

const express = require('express');
const http = require('http');
const path = require('path');
const cors = require('cors');
const passport = require('passport');
const bodyParser = require('body-parser');

const {
  serverConfig: { httpPort },
} = require('./config/serverConfig');

const server = express();

const corsOptions = {
  origin: 'http://ipAddressOfFrontEnd:8080',
  optionsSuccessStatus: 200,
  credentials: true,
};
server.use(cors(corsOptions));
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());

const serverConnection = http.createServer(server);

serverConnection.listen(
  httpPort,
  console.log(`Server Listening on port ${httpPort}`)
);

头盔设置

app.use(
    helmet.contentSecurityPolicy({
      directives: {
        defaultSrc: [self],
        scriptSrc: [self, ...scripts, unsafeInline],
        styleSrc: [self, ...styles, unsafeInline],
        imgSrc: [self],
      },
      setAllHeaders: true,
    })
  );

  app.use(
    helmet.expectCt({
      enforce: true,
      maxAge: 123,
    })
  );

  app.use(
    helmet.hsts({
      maxAge: 31536000,
      includeSubDomains: true,
      preload: true,
    })
  );

  app.use(helmet.permittedCrossDomainPolicies());
  app.use(helmet.dnsPrefetchControl({ allow: false }));
  app.use(helmet.referrerPolicy({ policy: 'same-origin' }));
  app.use(helmet.frameguard({ action: 'sameorigin' }));
  app.use(helmet.xssFilter({ setOnOldIE: true }));
  app.use(helmet.noCache());
  app.use(helmet.hidePoweredBy());
  app.set('x-powered-by', false);
  app.use(helmet.noSniff());

被点击以获得令牌的路线

const express = require('express');
const ntlm = require('express-ntlm');
const JWT = require('jsonwebtoken');
const passport = require('passport');

const router = express.Router();

if (process.env.NODE_ENV === 'production') {
  router.use(
    ntlm({
      // ldap settings
    })
  );
}

// @route   GET api/user/generateToken
// @desc    Create JWT Token
// @access  Public
router.get('/generateToken', (req, res) => {
  const errors = {};

  const username =
    process.env.NODE_ENV === 'production'
      ? req.ntlm.UserName.toLowerCase()
      : process.env.username.toLowerCase();

  // removed remainder of code as request does not reach this route
})

我已经删除了一些我认为不相关的代码,请告诉我是否还有其他需要。如您所见,我在生产中使用ntlm。我已经将控制台记录下来,并且一切正常。实际上,如果我直接在浏览器中转到URL http://IPAddressForServer:5000/api/user/generateToken,则会得到一个网络令牌,因此路由可以按预期工作。我已经尝试调试,但是路由甚至没有被axios请求拒绝。我提供了我的cors和头盔代码,以防万一,原因是这些

控制台错误 GET http://IPAddressForServer:5000/api/user/generateToken 400(错误请求)

当我在控制台上记录err.response时

config:
 adapter: ƒ (e)
 baseURL: "http://IPAddressForServer:5000//"
data: undefined
headers:
 Accept: "application/json, text/plain, */*"
 Authorization: {}
 __proto__: Object
 maxContentLength: -1
 method: "get"
 timeout: 0
 transformRequest: [ƒ]
 transformResponse: [ƒ]
 url: "http://IPAddressOfServer:5000/api/user/generateToken"
 validateStatus: ƒ (e)
 arguments: (...)
 caller: (...)
 length: 1
 name: "validateStatus"
 prototype: {constructor: ƒ}
 __proto__: ƒ ()
 [[FunctionLocation]]: bundle.js:17
 [[Scopes]]: Scopes[3]
 xsrfCookieName: "XSRF-TOKEN"
 xsrfHeaderName: "X-XSRF-TOKEN"
 __proto__: Object
 data: "Bad Request"
headers:
 cache-control: "no-store, no-cache, must-revalidate, proxy-revalidate"
 content-type: "text/plain; charset=utf-8"
 expires: "0"
 pragma: "no-cache"
 __proto__: Object
request: XMLHttpRequest
 onabort: ƒ ()
 onerror: ƒ ()
 onload: null
 onloadend: null
 onloadstart: null
 onprogress: null
 onreadystatechange: ƒ ()
 ontimeout: ƒ ()
 readyState: 4
 response: "Bad Request"
 responseText: "Bad Request"
 responseType: ""
 responseURL: "http://IPAddressOfServer:5000/api/user/generateToken"
 responseXML: null
 status: 400
 statusText: "Bad Request"
 timeout: 0
 upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: 
 null, onerror: null, onload: null, …}
 withCredentials: false
 __proto__: XMLHttpRequest
 status: 400
 statusText: "Bad Request"

0 个答案:

没有答案