在Express上使用axios挂起电话

时间:2019-05-29 09:21:58

标签: javascript node.js express

我试图使用带有Express的axios对api进行非常简单的调用,却不知道为什么它总是在浏览器中挂起

这是我的路线

var express = require("express");
var router = express.Router();
const controller = require("../../controllers/issues.controller");
/* GET ALL ISSUES */
router
  .route('/')
  .get(controller.getAllIssues);

这是我的控制人

var axios = require("axios");
const url = "https://redmine-mock-api.herokuapp.com/api/v1/issues?after=2019-04-13T12:00";


exports.getAllIssues = () => {
  const res = axios.get(url)
    .then(res => console.log(res.data))
    .catch(err => console.log("Axios err: ", err));
}

这是app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./src/api/routes/v1/index');
var usersRouter = require('./src/api/routes/v1/users');
var issuesRouter = require('./src/api/routes/v1/issues');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/v1/users', usersRouter);
app.use('/v1/issues', issuesRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

在浏览器上,它始终处于等待状态,我已经尝试从.then进行等待/异步,并且不知道我在做什么错。当我在同一文件上具有路由和控制器时,它正在工作。有人给小费吗?

1 个答案:

答案 0 :(得分:0)

我认为问题出在控制器上。由于您从不运行 public void Configuration(IAppBuilder app) { app.UseCors(Owin.Cors.CorsOptions.AllowAll); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies", CookieManager = new SystemWebChunkingCookieManager(), }); //// Bearer token authentication middleware.(Ex: request from web clients,ajax calls able to pass authenticated bearer info) app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters { ValidAudience = ConfigurationManager.AppSettings["ida:Audience"], TokenReplayCache = new TokenReplayCache(new MemoryCacheProvider()) }, Tenant = ConfigurationManager.AppSettings["ida:Tenant"], Provider = new OAuthBearerAuthenticationProvider { OnValidateIdentity = ctx => { //// Retrieve user roles from the request. var authenticationTicket = ctx.Ticket; if (authenticationTicket.Identity.IsAuthenticated) { ////Use the block when role/user specific authorization needs and to modify the user identity claims based on requirement } return Task.FromResult(0); }, OnRequestToken = ctx => { return Task.FromResult(0); } } }); //// Non Bearer authentication middleware. (Ex: request secured web api call directly from URL/Web API server scope it self) app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = ClientId, ClientSecret = ConfigurationManager.AppSettings["ida:AppKey"], Authority = Authority, PostLogoutRedirectUri = PostLogoutRedirectUri, AuthenticationMode = AuthenticationMode.Active, ResponseType = "code id_token", CallbackPath = new PathString("/"), Notifications = new OpenIdConnectAuthenticationNotifications() { SecurityTokenValidated = context => { if (context.AuthenticationTicket.Identity.IsAuthenticated) { ////Use the block when role/user specific authorization needs and to modify the user identity claims based on requirement } return Task.FromResult(0); }, AuthorizationCodeReceived = async context => { var code = context.Code; ClientCredential credential = new ClientCredential(ClientId, Models.ConfigurationData.GraphSecret); string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID)); Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, GraphResource); }, RedirectToIdentityProvider = context => { if (context.ProtocolMessage.RedirectUri == null) { ////To set the reply/redirect Url based on the request host environment. ////Hosting env details we get only through the owin context in startup and this is the delegate to set reply URL in OWincontext before the authentication. string ReplyAddress = context.Request.Scheme + "://" + context.Request.Host + "/"; context.ProtocolMessage.RedirectUri = ReplyAddress; } //context.OwinContext.Authentication.User.Identity.IsAuthenticated = true; if (context.OwinContext.Authentication.User.Identity.IsAuthenticated && context.ProtocolMessage.RequestType != IdentityModel.Protocols.OpenIdConnect.OpenIdConnectRequestType.Logout) { ////To avoid infinite loop of redirections in request if user is authenticated and unauthorized. context.HandleResponse(); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; } return Task.FromResult(0); } }, TokenValidationParameters = new TokenValidationParameters { RoleClaimType = "roles", TokenReplayCache = new TokenReplayCache(new MemoryCacheProvider()) }, }); System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = System.IdentityModel.Claims.ClaimTypes.NameIdentifier; } 变量函数(只需对其进行定义),因此什么也不会发生,并且由于响应没有被发送回……它正在挂起。

res

异步方法看起来非常相似

exports.getAllIssues = (req, res) => {
  axios.get(url)
    .then(axRes => {
        console.log(axRes.data)
        // this below line is what closes the loop on waiting for the controller
        res.json(axRes.data);
    })
    .catch(res.json);
}

您可以在http://expressjs.com/en/api.html#res.json

处了解不同的快速exports.getAllIssues = async (req, res) => { try { const axRes = await axios.get(url); res.json(axRes.data); } catch(err) { res.send(err); } } 方法等