2017-07-17 90 views
0

如果我從客戶端發送POST如/image/cover/image/sub/,路由器功能根本不起作用,所以它發送404。它應該工作,但我從字面上不知道。我從來沒有遇到過這種情況,它無緣無故。koa路由器不工作,發送404

路由器

import Router from 'koa-router' 

const router = new Router({ prefix: '/image' }) 

router.post('/cover', async (ctx, next) => { 
    let URLpath = ctx.request.body.files.cover.path 
    ctx.body = { url: URLpath } 
}) 

router.post('/sub', async (ctx, next) => { 
    let URLpath = ctx.request.body.files.sub.path 
    ctx.body = { url: URLpath } 
}) 

export default router 

日誌

<-- POST /image/cover 
    --> POST /image/cover 404 33ms - 

導入代碼(修訂版) 路由器/ index.js 進口從 'KOA-撰寫'

組成
import accountRouter from './account' 
import mypageRouter from './mypage' 
import imageRouter from './image' 
import postRouter from './post' 

const routes = [ 
    accountRouter, 
    mypageRouter, 
    imageRouter, 
    postRouter 
] 

export default() => compose([].concat(
    ...routes.map(r => [r.routes(), r.allowedMethods()]) 
)) 

app.js

import Koa from 'koa' 
import serve from 'koa-static' 
import logger from 'koa-logger' 
import views from 'koa-views' 
import session from 'koa-session' 
import passport from 'koa-passport' 
import bodyParser from 'koa-body' 
import path from 'path' 

import routes from './routes' 
import config from './config' 
import form from './util/formidable' 

import mongoose from 'mongoose' 
mongoose.Promise = global.Promise 

mongoose 
    .connect(config.MONGODB_URI) 
    .then(startApp).catch(::console.error) 

function startApp() { 
    const app = new Koa() 
    const port = process.env.PORT || 3000 
    const dist = __dirname + '/views/' 
    console.log(form) 
    const bpOption = { IncomingForm: form, multipart: true } 

    app.keys = ['secret', 'key']; 
    require('./util/passport') 

    app 
     .use(logger()) 
     .use(serve(dist)) 
     .use(session({}, app)) 
     .use(bodyParser(bpOption)) 
     .use(passport.initialize()) 
     .use(passport.session()) 
     .use(views(__dirname+'/views', { extension: 'pug'})) 
     .use(routes()) 

    app.listen(port,() => console.log(`[!] Server is Running on ${port}`)) 
} 
+0

你能分享你導入這個代碼嗎? –

+0

@AramilRey我剛更新了! –

回答

1

您需要幫助功能:

// @help function record route table map

'use strict'; 

const fs = require('fs'); 
const resolve = require('path').resolve; 

module.exports = function record(router, filename) { 
    const routeTable = fs.createWriteStream(resolve(__dirname, filename)); 
    routeTable.write(`Update Date: ${new Date().toString()}\n\n`); 
    for (let len = router.stack.length, i = 0; i < len; i += 1) { 
    const route = router.stack[i]; 
    routeTable.write(`URL:${route.path}\t${route.methods.join('|')}\n`); 
    } 
    routeTable.end(); 
}; 

那麼你可以通過

const record = require('./record'); 
record(routeApp, '.routerc') 
涉及它

你會得到.routerc文件(路線圖)的內容,如:

URL: /a/c/c POST 
URL: /b/a/d GET 

它可以幫助你解決問題。也許工作。祝你好運!