首页 > 解决方案 > Axios - NodeJS 总是返回 500 内部服务器错误

问题描述

我有一个用于 api 网关的 node-express 项目。

这是我的网关代码;

app.use(cors({
    origin: 'http://localhost:8081',
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    optionsSuccessStatus: 200
}));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
//app.use(morgan('combined'));
app.use(cacheControl({
    noCache: true
}));
dotenv.load();
// Serve static assets
app.use(express.static(path.join(__dirname, 'dist')));

axios.interceptors.response.use((response) => {
    return {
        success: true,
        status: response.status,
        data: response
    };
}, error => {
    let e = error;
    let errObject = {
        response: {
            data: e.response.data
        }
    };
    return Promise.reject(errObject);
});
app.post('/service', (req, res) => {
       if (req.body.type.indexOf('auth' > -1)) {
          let payload = {
              url: process.env.DEV_ENDPOINT + req.body.type,
              method: req.body.method,
              data: req.body.data
          };
           try {
              return axios(payload).then(function(response){
                   res.send(response);
               }).catch((error) => {
                   res.send(error);
               })
           } catch (e) {
               console.log("error");
               console.log(e);
           }
       } else {
           // verify it first
       }
});

app.listen(PORT, error => (
  error
    ? console.error(error)
    : console.info(`Listening on port ${PORT}. Visit http://localhost:${PORT}/ in your browser.`)
));

module.exports = app;

现在,问题就在这里;在拦截器中,axios 总是会捕获错误。错误;

500内部服务器错误。如果您是本网站的管理员,请阅读此 Web 应用程序的日志文件和/或 Web 服务器的日志文件以找出问题所在。

在邮递员中,我正在向实际的 api 及其工作发送请求。但是在 axios 中,不知何故,它不起作用。它总是发送错误文本。

标签: node.jsexpressaxios

解决方案


您可以在控制台中看到有关错误的信息。

 app.post ('/ service', (req, res) => {
 if (req.body.type.indexOf ('auth'> -1))

 // Here in the .then, somehow introduce it
 // in your code, try it.
 .then (res => {
        console.log (res);

该内部服务器错误有可能的原因和可能的解决方案,请查看以下链接,虽然它来自 Laravel,但您可以有一个想法,因为原因中所述的内容作为一个概念非常好记的错误。

同样的事情发生在我身上,在我的情况下,我在 Schema 中的数据类型中有一个错误,此外还有一个与 this.axios.post 不对应的修复正在发生。另外,我没有在控制台中显示答案,因为我把它放在代码中。呵呵,我是 APIREST 新手

如果它对您有帮助,我的代码是:

  this.axios.post ('/ inventory', 
  this.ArticlesForm)
  .then (res => {
        console.log (res);
      this.invent.unshift (res.data)
      })
    .catch (function (error) {//
    console.log (error.toJSON); //
    console.log ('in inventory.vue')
});
},

在我的控制器中,我有以下内容:

router.post ('/ inventory', async (req, res) => {
const body = req.body;
try {
const DB note = await Invent.create (body);
res.status (200) .json (notaDB);
} catch (error) {
 // return res.status (500) .json ({
 // message: 'An error occurred in post',
//error
//})

 }

照原样,正确插入柱子。


推荐阅读