我正在为使用Ajax请求从MongoDB数据库中提取数据而苦苦挣扎。在使用React路由器时,无法向快速服务器发出AJAX请求
该应用程序使用React编写,使用React-Router进行路由和坐在Express服务器上。我正在使用whatwg-fetch
来处理ajax调用。
当我试图让Ajax调用,我得到以下错误:
parsing failed: SyntaxError: Unexpected token < in JSON at position 0
我认为问题在于阵营-路由器。当我直接导航到Ajax调用指定的URL,我得到以下错误:
Warning: [react-router] Location "/levelsList" did not match any routes
所以它看起来好像反应,路由器拦截了请求的URL,并试图传递寻呼,这没有按在React-Router中不存在。那么,如何绕过React-Router进行ajax调用,并使用Express路由器呢?
这里有更多的代码:
server.js
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const path = require('path');
const httpProxy = require('http-proxy');
const mongoose = require('mongoose');
const config = require('./webpack.dev.config')
//Mongoose Schema
const Level = require('./data/models/Level');
//DB SETUP
mongoose.connect('mongodb://Localhost/Academy');
// SERVER SETUP
const app = express();
const router = express.Router();
var publicPath = path.resolve(__dirname, 'public');
compiler=webpack(config);
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
stats: {colors: true}
}));
app.use(webpackHotMiddleware(compiler, {
log: console.log
}));
app.use(express.static(publicPath));
//Routes
app.get('*', function(req, res){
res.sendFile(path.resolve(publicPath, 'index.html'));
})
app.get('/levelsList', function(req, res){
console.log('test');
Level.find({})
.exec(function(err, levels){
if (err){
res.send('error has occurred');
} else {
console.log(levels);
res.json(levels);
}
})
})
app.listen(3000, function(){
console.log('Server running on port 3000');
});
这里是行动的创建者,这使得Ajax调用,那么它应该转储信息到我的终极版店
import 'whatwg-fetch';
export function qualDetails(){
const data = fetch('/levelsList')
.then(function(res){
return res.json()
})
.then(function(json){
console.log('parsed json: ', json)
})
.catch(function(ex){
console.log('parsing failed: ', ex) // This is where the error message is coming from
});
console.log(data);
return {
type: 'COURSE_DETAILS',
payload: data
}
}
谢谢你,但它似乎并没有奏效 - 我仍然收到相同的错误信息 – Chris
@Chris更新了我的答案,我只是意识到它是你的'app.get('*')'匹配你的路线,并重定向以作出反应。 React然后尝试路由与反应路由器 – Okazari
啊 - 在您的编辑后,它似乎工作!辉煌,谢谢! – Chris