如题,使用express+http-proxy-middleware代理拿不到数据
这是app.js
的内容
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// 代理插件
var proxy = require('http-proxy-middleware');
// 跨域插件
var cors = require('cors');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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');
});
// 设置代理
app.use('/api', proxy({
target: 'https://api.douban.com',
changeOrigin: true
}));
app.listen(4000, function() {
console.log('http://localhost:4000')
});
module.exports = app;
抓取的是豆瓣音乐的api,然后客户端的代码如下
function ajax(url) {
var xml = new XMLHttpRequest();
xml.open('GET', url, true);
xml.onreadystatechange = function() {
if (xml.readyState == 4 && xml.status == 200) {
console.log(JSON.parse(xml.responseText));
}
}
xml.send();
}
ajax('http://localhost:4000/v2/music/search?q=周杰伦')
然而报错,拿不到数据,跨域确实没有了,但是却拿不到数据。
api接口地址是豆瓣音乐api,是可以正常打开的。不知道是不是我哪里写错了,大佬们帮看看哇,感激不尽。
api路径定义不对,读一下http-proxy-middleware的文档