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

怎么使用 application/json 类型的解析器 #294

Open
chakson opened this issue Sep 13, 2022 · 6 comments
Open

怎么使用 application/json 类型的解析器 #294

chakson opened this issue Sep 13, 2022 · 6 comments

Comments

@chakson
Copy link

chakson commented Sep 13, 2022

使用 Content-Type: application/x-www-form-urlencoded 可以正常返回数据,
使用 Content-Type: application/json 无法正常解析 req.body 的请求数据,
请问这个要怎么配置

@jaywcjlove
Copy link
Owner

const { password, username } = req.body;
if (password === '888888' && username === 'admin') {
return res.json({
status: 'ok',
code: 0,
token: "sdfsdfsdfdsf",
data: {
id: 1,
username: 'kenny',
sex: 6
}
});
} else {
return res.json({
status: 'error',
code: 403
});
}

我测试示例,可以获取 body 参数,不清楚你是怎么请求数据的

@chakson
Copy link
Author

chakson commented Sep 13, 2022

我在 postman 里面模拟请求,user.js 和你写得一样。
postman 请求截图如下:
失败:
image

成功:
image

@jaywcjlove
Copy link
Owner

image

@chakson 不太清楚你怎么使用的,目前我测试没有问题,请看上图

@jaywcjlove
Copy link
Owner

'POST /api/login/account': login,

测试的就这个示例。

@chakson
Copy link
Author

chakson commented Sep 13, 2022

在 express 中加入 body-parser,这样 Content-Type: application/json 就可以解析了

const express = require('express');
const path = require('path');
const apiMocker = require('mocker-api');
const bodyParser =require('body-parser');

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

apiMocker(app, path.resolve('./mocker/index.js'));
app.listen(8000);

你这个项目是不是有 application/json 相关的配置,这几个配置看不懂怎么用

image

@jaywcjlove
Copy link
Owner

const defaultOptions: MockerOption = {
changeHost: true,
pathRewrite: {},
proxy: {},
// proxy: proxyConf: {},
httpProxy: {},
// httpProxy: httpProxyConf: {},
bodyParserConf: {},
bodyParserJSON: {},
bodyParserText: {},
bodyParserRaw: {},
bodyParserUrlencoded: {},
watchOptions: {},
header: {},
priority: 'proxy',
withFullUrlPath: false
}
options = { ...defaultOptions, ...options };

@chakson 是支持配置的默认不需要的样子

在 webpack 示例中默认没有配置,支持 json 解析

apiMocker(devServer.app, path.resolve('./mocker/index.js'), {
proxy: {
'/repos/(.*)': 'https://api.github.com/',
},
changeHost: true,
})

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

2 participants