【问题标题】:request failed with status code 400请求失败,状态码 400
【发布时间】:2017-06-02 10:14:34
【问题描述】:

我在 nodejs 中运行服务器,在执行服务器代码时出现错误 “(节点:7692)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:2):错误:请求失败,状态码为400 (节点:7692)DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将终止 Node.js 进程并使用非零退出代码。

这是我的 serverrender.js 代码

import axios from 'axios';
import config from './config';

axios.get('${config.serverUrl/api/contests')
.then(resp=>{
    console.log(resp.data);
});

这是我的 srver.js 代码

    import config from './config';
    import apiRouter from './api';
    import express from 'express';
    import path from 'path';
    import sassMiddleware from 'node-sass-middleware';

    import './serverRender';
    const server=express();
    server.set('view engine','ejs');

    server.use(sassMiddleware({
        src:path.join(__dirname,'sass'),
        dest:path.join(__dirname,'public')
    }));

    server.get('/',(req,res)=>{

        res.render('index',{
            content:"... "
        });


});
server.use(express.static('public'));

server.use('/api',apiRouter);

server.listen(config.port, config.host, () =>{
    console.info('express listening on port ',config.port);
});

【问题讨论】:

  • Unhandled Promise Rejection 是因为您没有 catch 回调。至于其他,检查网址;这是${config.serverUrl/api/contests。你有 ${ 并且括号没有关闭。你确定这是正确的?

标签: node.js reactjs


【解决方案1】:

您需要将配置变量的左括号括起来。

import axios from 'axios';
import config from './config';

axios.get(`${config.serverUrl}/api/contests`)
  .then(resp=>{
    console.log(resp.data);
  })  
  .catch(error=>{

  });

【讨论】:

    【解决方案2】:

    您应该在 get 调用中添加一个 catch:

    import axios from 'axios';
    import config from './config';
    
    axios.get('${config.serverUrl/api/contests')
      .then(resp=>{
        console.log(resp.data);
      })  
      .catch(error=>{
    
      });
    

    【讨论】:

    • 现在我收到一个错误作为 throw er; // 未处理的“错误”事件
    猜你喜欢
    • 2021-11-09
    • 2019-09-29
    • 2020-10-03
    • 2020-10-21
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    相关资源
    最近更新 更多