Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mock-server 获取restful风格路径参数 #3396

Open
coymaple opened this issue Aug 20, 2020 · 3 comments
Open

mock-server 获取restful风格路径参数 #3396

coymaple opened this issue Aug 20, 2020 · 3 comments

Comments

@coymaple
Copy link

我有一条这样的 api

export function delMenu(id){
  return request({
    url: '/vue-admin-template/menu/del/'+id,
    method: 'delete',
  })
}

对应的 mock 是

{
    url: '/vue-admin-template/menu/del/[0-9]{1,3}',
    type: 'delete',
    response: (config) => {}
 }

我想知道在mockserver中,用什么样的方法可以拿到restful风格的url中的参数,试过 config.params ,是一个空对象。

@passioncsu
Copy link

这样可以拿到
const { id } = req.params
如下

export const updateOperator = (req: Request, res: Response) => {
  const { id } = req.params
  const { article } = req.body
  for (const v of articleList) {
    if (v.id.toString() === id) {
      return res.json({
        code: 200,
        data: article
      })
    }
  }
  return res.json({
    code: 404,
    message: '信息不存在'
  })
}

你的写法没用过, 是不是应该?

{
    url: '/vue-admin-template/menu/del/{id}',
    type: 'delete',
    response: (config) => {}
 }

@coymaple
Copy link
Author

我的写法是 express 中restful 路径参数的标准写法。可能 mock.js 不支持这种写法。

除了正则表达式的写法外,/menu/del/{id}/menu/del/:id 无法在 url 为 /menu/del/1 时,被mockjs拦截,进入webpack-dev-server。

@luocong2016
Copy link

luocong2016 commented Jul 23, 2021

mock-server.js

我想使用这样的 mockURL

url: `/code/:code`
// for mock server
const responseFake = (url, type, respond) => {
  return {
    // 应该是这里的问题 阻止了 /xxx/:id 这种写法
    url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
    type: type || 'get',
    response(req, res) {
      console.log('request invoke:' + req.path);
      res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond));
    },
  };
};

我改成这样是可以的

// for mock server
const responseFake = (url, type, respond) => {
  const _url = `${process.env.VUE_APP_BASE_API}${url}`;
  return {
    url: /\/:/.test(_url) ? _url : new RegExp(_url),
    type: type || 'get',
    response(req, res) {
      console.log('request invoke:' + req.path);
      res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond));
    },
  };
};

结果显而易见

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants