配置代码
proxyTable: {
'/api': {
target: 'http://127.0.0.1:8088/api',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
node 代码
const express = require('express')
const bodyParser = require('body-parser')
const superagent = require('superagent')
const cheerio = require('cheerio')
const api = require('./api')
const app = express();
app.use(bodyParser.urlencoded({ extended: true }))
// parse application/json
app.use(bodyParser.json())
app.post('/api/login', function (req, res) {
if(req.body.username == 'admin' && req.body.password == '123456') {
res.json({
errno: 1,
msg: '登录成功!'
})
} else {
res.json({
errno: 0,
msg: '登录失败!用户名或密码错误!'
})
}
})
app.get('/api/getCrawler', function (req, res, next) {
// res.send('hello world');
superagent.get('https://cnodejs.org/')
.end((err, sres) => {
if(err) {
return next(err);
}
const $ = cheerio.load(sres.text);
let items = [];
$("#topic_list .topic_title").each(function (index, element) {
items.push({index: index+1,title: $(this).attr("title"), href: $(this).attr("href")})
})
res.json({
errno: 0,
items: items
});
})
})
app.listen(8088, function () {
console.log('app is listening 8088')
});
let loginParams = { username: this.logForm.account, password: this.logForm.checkPass };
this.axios.post('/api/login',loginParams).then(response => {
this.logining = false;
let {data, status} = response;
if(data.errno == '1') {
sessionStorage.setItem('user', JSON.stringify(loginParams));
this.$router.push({path: '/main'})
} else {
this.$notify({
title: '错误',
message: data.msg,
type: 'error'
})
}
})
报错
貌似代理没有成功。但是我在node中设置跨域之后也没用。所以是不是node写的不对?
更新: node中添加以下代码设置跨域访问后,接口用http://localhost:8088/api/login,在vue中可以访问。
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
所以应该是代理的问题。。。
应该是代理成功了,不然会出现404的情况。
看错误是说服务器响应是空的,你可以先使用PostMan之类的工具把代理服务器的接口调通。
仔细调一下那个
8088
端口的服务