客户端JavaScript没有find我的url

我想用nodejs和javascript / jquery开发一个客户端服务器端,但我卡住了。 我有一个很大的forms,用户提交和数据发送到/getDataurl,并完美的作品。 但现在我的问题是,当我想从/getData数据到我的客户端。

这是我的客户文件:

 var client = {}; client.start = function () { client.getData(); }; client.cb_get = function () { var data={}; if (this.readyState == 4 && this.status == 200) { data= JSON.parse(this.responseText); alert("We get the data" + JSON.stringify(data, null, 4)); client.chart(data); } else { alert("Sorry this page is not allow without processing any form"); } }; client.get = function(req, cb) { var xhr = new XMLHttpRequest(); xhr.open("GET", req, true); xhr.onreadystatechange = cb; xhr.send(); }; client.getData= function () { var req="http://localhost:3000/getData"; client.get(req,client.cb_get); }; client.chart= function (data) { //Display data as charts using jquery in an other html page. }; window.onload = setTimeout(client.start, 1); HTMLElement.prototype.has_class = function (c) { return this.className.indexOf(c) >= 0; }; 

但是我总是有404错误,我不知道为什么。

我的服务器文件:

 var express = require('express') bodyParser =require("body-parser"); routes= require('./router.js'); var app= express(); app.use(express.static(__dirname + '/')); //Here we are configuring express to use body-parser as middle-ware. app.use(bodyParser.urlencoded({ extended: false })); //define our routes app.get('/', routes.index); //open home page app.get('/simulation', routes.simulation); app.get('/chartData', routes.chartData); app.post('/getData', routes.getData); //In case of malicious attacks or mistyped URLs app.all('*', function(req, res){ res.send(404); }) var server = app.listen(3000, function () { var host = server.address().address var port = server.address().port console.log('Example app listening at http://%s:%s', host, port) }) 

我的路由器文件:

 module.exports.index= function(req, res){ fs.readFile('index.html', function(err, page) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(page); res.end(); }); }; module.exports.simulation= function(req, res){ fs.readFile('simulation.html', function(err, page) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(page); res.end(); }); }; module.exports.chartData= function(req,res) { fs.readFile('chartPage.html', function(err, page) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(page); res.end(); }); }; module.exports.getData= function(req,res) { var data= {}; data= req.body; res.send(JSON.stringify(data, null, 4)); console.log(req.body); }; 

那我哪里错了? 此外,当我提交时,我/getdata页面打开(正常由于action= /getData指定在我的表单标签),但我想直接打开我的HTML页面图表。 我怎样才能做到这一点?

对不起,我很长的职位,但我真的需要帮助。

你的ajax请求呢

 xhr.open("GET", "http://localhost:3000/getData", true); 

你的路线听

 app.post('/getData', routes.getData); 

注意你是如何发送一个GET请求,并侦听一个POST请求,这不是一回事,所以你最终在404路由。

您必须更改ajax请求,并发送POST请求或路由并侦听GET请求。