我正在努力制作ajax请求从MongoDB数据库中提取数据。
App使用React编写,使用React-Router进行路由并坐在Express服务器上。我使用whatwg-fetch
来处理ajax调用。
当我尝试进行ajax调用时,出现以下错误:
parsing failed: SyntaxError: Unexpected token < in JSON at position 0
我认为问题在于React-Router。当我直接导航到ajax调用中指定的URL时,我收到以下错误:
Warning: [react-router] Location "/levelsList" did not match any routes
因此看起来React-Router正在拦截对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调用的动作创建者,然后将该信息转储到我的redux商店
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
}
}
答案 0 :(得分:2)
您应该尝试在路线声明后放置app.get(*)
。
//Routes
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.get('*', function(req, res){
res.sendFile(path.resolve(publicPath, 'index.html'));
})
app.use(express.static(publicPath));
据我所知,express将以完全相同的顺序尝试所有路径。
实际上/levelslist
将与您的get(*)
匹配,然后做出反应将尝试在/levelslist
我通常会在/app
下显示我的静态前端应用,并在/api
前缀下显示我的api路由。它确实有助于防止任何混淆
希望它有所帮助。