请教webpack和nodejs的跨域问题,ajax总是404。万分感谢啊!
各位师兄好啊。我在做一个用户名登录功能测试的时候,利用ajax以及webpack服务器post跨域请求express服务器的时候遇到点麻烦。我先输入username,然后onblur之后发送用户名至后台,后台res.send(req.body.username),然后ajax的success把data打印出来看。然而,却总是404,估计是跨域失败的问题?
webpack代码如下:
var path=require('path');
var webpack=require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
var proxy=require("http-proxy-middleware");
module.exports={
devtool: 'eval-source-map',
entry: {
index: [
'webpack-dev-server/client?http://localhost:8181',
'webpack/hot/only-dev-server',
'./public/javascripts/entry.js'
],
vendor: ['react', 'react-dom', 'react-router', 'jquery']
},
output:{
// path: path.resolve(__dirname,'./build'),
filename:'bundle.js',
publicPath: '/'
},
devServer: { //这儿有问题? 重定向失败的问题?
// contentBase: "./",
inline: true,
historyApiFallback: true,
port:8181,
host: "127.0.0.1",
proxy: [
{
context: "/*/*", //跨域的路由设置
target: "http://localhost:3000", //跨到哪儿去^-^
changeOrigin: true //允许跨域,必不可少
}
]
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets:['es2015', 'stage-0', 'react'],
plugins: [
['import', {libraryName: 'antd', style: 'css'}]
]
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader!sass-loader'
})
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=8192'
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new ExtractTextPlugin('style.css'),
new CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.js'
})
]
}
express服务端代码如下,主要是最下面一点的设置:
var environment=process.env.NODE_ENV;
var webpack=require('webpack');
var config;
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 consolidate = require('consolidate');
var app = express();
if (environment==='production') {
config=require('./webpack.config.prod.js');
} else if (environment==='development') {
config=require('./webpack.config.dev.js');
} else {
console.log('Please define NODE_ENV first');
}
var compiler=webpack(config);
if (environment==='production') {
var WebpackDevMiddleware=require('webpack-dev-middleware');
app.use(WebpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
} else if (environment==='development') {
var WebpackHotMiddleware=require('webpack-hot-middleware');
app.use(WebpackHotMiddleware(compiler));
}
var index = require('./routes/index');
var users = require('./routes/users');
// view engine setup
// app.engine('html', consolidate.ejs);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// 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, 'views')));
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.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//here my codes
app.post('/check/:item', function(req, res) {
if (req.params.item=="user") {
var user=req.body.username;
res.send(user);
}
})
app.listen(3000, function(err) {
if (err) {
console.error(err);
} else {
console.log("listen on port 3000");
}
})
最后是ajax的代码,其他地方都没问题,onchange取到user.value的值然后发送后台:
$.ajax({
type: "post",
url: "check/user", //配置过devServer中的proxy
// dataType: "json",
data: {
username: user.value
},
success: (data)=>{
console.log(data, $.type(data));return;
},
error: (xhr)=>{
console.log("出错啦:"+xhr.status)
}
});
尝试修改过的部分包括以下,但是都不行:
- ajax的url写成 /check/user 或者localhost:服务器端口号
- webpack的devServer的contentBase处,以及proxy写成:
proxy: {
"/check/*": {
secure: false,
target: "http://localhost:3000", //跨到哪儿去^-^
changeOrigin: true //允许跨域,必不可少
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
算了,本来准备关闭问题,还是把问题的出处说一下。
ajax一直出现404的原因,并不是跨域不成功的问题,也不是ajax写法的问题,而是后台app.js里面的404错误捕获造成的:
我经过把后台所有代码一段一段屏蔽查看影响的时候,发现屏蔽了以上代码后,ajax就能正常返回data的值,而不是404错误。但是我不太理解为什么会这样?
这个地方难道不是只有在出现404错误的时候才把错误返回到前台吗,为什么并没有错误就返回404???
app.post('/check/:item', function(req, res) {
这里你是字符串那就是固定死了,就只会匹配/check/:item,应该用正则匹配