I try to use json-server in vue-cli project, set proxy api to jsonServer.
var jsonServer = require('json-server')
var apiServer = jsonServer.create()
var apiRouter = jsonServer.router('db.json')
var apiMiddlewares = jsonServer.defaults()
apiServer.use(apiMiddlewares)
apiServer.use(apiRouter)
apiServer.listen(port + 1, function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:' + (port + 1) + '\n')
})
dev: {
env: require('./dev.env'),
port: 8888,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api/': 'http://localhost:8889/'
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false,
}
in src file:
ready () {
let resource = this.$resource('api{/type}');
resource.save({type: 'getBoardList'}, {hello: 'world'})
.then(function (data) {
console.log(data)
}, function (error) {
console.log(error)
})
},
in dev server :8888 i request api/getBoardList, in my surpose it will proxy to localhost:8889/getBoardList, and I direct visit 'localhost:8889/getBoardList' show the json, but In proxy Not.
network return
{}
No Properties
and 404 Not Found
I tried it.
I think... proxyTable don't rewrite path. So, http://localhost:8888/api/getBoardList is proxy to http://localhost:8889/api/getBoardList
And, proxyTable is option to pass to http-proxy-middleware.
You can use followings for resolve it.
dev: {
env: require('./dev.env'),
port: 8888,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api/': {
target: 'http://localhost:8889/',
pathRewrite: { '^/api/': '/' },
},
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false,
}
thank you for the answer. @zakuro9715
you right as my config
http://localhost:8888/api/getBoardList is proxy to http://localhost:8889/api/getBoardList
'/api/': 'http://localhost:8889/' means request to 'api/‘, proxy to host http://localhost:8889/ with whole paths, maybe can say so.
my solve is change json-server config, use router from 'api' path
in apiRouter part
before:
apiServer.use(apiRouter)
now
apiServer.use('/api', apiRouter)
Most helpful comment
And,
proxyTableis option to pass to http-proxy-middleware.You can use followings for resolve it.