相对较新的node.js,试图从Angular2获取一个JS对象到我的node.js路由,但我总是在索引0"得到一个标准的"意外的令牌等等。来自本机对象解析器。
对象到达我的节点工厂就好了,但在发布到路由时失败了。
这是发送到路由的JSON:
{"SQLServerHostName":"MININT-MT0DKDT","SQLServerDBName":"ContosoRetailDW","SQLServerUserName":"svc_sql_D3","SQLServerPassword":"Inspur123#@!","StoredProcedureName":"[dbo].[d3Test]"}
这是我在开发控制台中收到的错误。
angular2.dev.js:23083 EXCEPTION:SyntaxError:意外的令牌S in 位于0BrowserDomAdapter.logError的JSON @ angular2.dev.js:23083BrowserDomAdapter.logGroup @ angular2.dev.js:23094ExceptionHandler.call @ angular2.dev.js:1185(匿名函数)@ angular2.dev.js:12591NgZone._notifyOnError @ angular2.dev.js:13635onError @ angular2.dev.js:13539Zone.run @ angular2-polyfills.js:1247(匿名函数)@ angular2.dev.js:13558zoneBoundFn @ angular2-polyfills.js:1220 angular2.dev.js:23083 STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:23083ExceptionHandler.call @ angular2.dev.js:1187(匿名函数)@ angular2.dev.js:12591NgZone._notifyOnError @ angular2.dev.js:13635onError @ angular2.dev.js:13539Zone.run @ angular2-polyfills.js:1247(匿名函数)@ angular2.dev.js:13558zoneBoundFn @ angular2-polyfills.js:1220 angular2.dev.js:23083 SyntaxError:JSON中的意外标记S. 位置0 at Object.parse(native) 在XMLHttpRequest.req.onload [as _onload](http://localhost:1557/app/services/xhr-factory.service.js:17:33) 在Zone.run(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:1243:24) 在Zone.run(http://localhost:1557/node_modules/angular2/bundles/angular2.dev.js:13558:32) 在XMLHttpRequest.zoneBoundFn(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:1220:26)
----- async gap -----错误 at _getStacktraceWithUncaughtError(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:2244:29) 在Zone.fork(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:2293:47) 在Zone.bind(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:1218:53) 在XMLHttpRequest.obj.addEventListener(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:1503:95) 在XMLHttpRequest.desc.set [as onload](http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:1449:19) 在eval(http://localhost:1557/app/services/xhr-factory.service.js:11:24) 在lib $ es6 $ promise $$ internal $$ initializePromise(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:515:10) at new lib $ es6 $ promise $ promise $$ Promise(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:806:10) 在_sendRequest(http://localhost:1557/app/services/xhr-factory.service.js:7:16) 在Object.post(http://localhost:1557/app/services/xhr-factory.service.js:39:28)
----- async gap -----错误 at _getStacktraceWithUncaughtError(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:2244:29) 在Zone.fork(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:2293:47) 在参数。(匿名函数)(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:1671:82)
----- async gap -----错误 at _getStacktraceWithUncaughtError(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:2244:29) 在Zone.fork(http://localhost:1557/node_modules/angular2/bundles/angular2-polyfills.js:2293:47) 在NgZone._createInnerZone(http://localhost:1557/node_modules/angular2/bundles/angular2.dev.js:13546:39) 在新的NgZone(http://localhost:1557/node_modules/angular2/bundles/angular2.dev.js:13412:32) 在createNgZone(http://localhost:1557/node_modules/angular2/bundles/angular2.dev.js:12475:12) 在PlatformRef_.application(http://localhost:1557/node_modules/angular2/bundles/angular2.dev.js:12550:31) at Object.bootstrap(http://localhost:1557/node_modules/angular2/bundles/angular2.dev.js:24805:64) 执行时(http://localhost:1557/app/boot.js:14:23) 在ensureEvaluated(http://localhost:1557/node_modules/systemjs/dist/system.src.js:3186:26) 在Object.execute(http://localhost:1557/node_modules/systemjs/dist/system.src.js:3304:13)BrowserDomAdapter.logError @ angular2.dev.js:23083ExceptionHandler.call @ angular2.dev.js:1188(匿名函数)@ angular2.dev.js:12591NgZone._notifyOnError @ angular2.dev.js:13635onError @ angular2.dev.js:13539Zone.run @ angular2-polyfills.js:1247(匿名函数)@ angular2.dev.js:13558zoneBoundFn @ angular2-polyfills.js:1220 angular2.dev.js:1206 Uncaught SyntaxError:JSON中的意外标记S. 位置0req.onload @ xhr-factory.service.ts:28Zone.run @ angular2-polyfills.js:1243(匿名函数)@ angular2.dev.js:13558zoneBoundFn @ angular2-polyfills.js:1220
这是调用工厂的Angular2组件
import {Component} from 'angular2/core';
import {WizardStepOneComponent} from './wizardStepOne.component'
import {WizardStepTwoComponent} from './wizardStepTwo.component'
import {WizardStepThreeComponent} from './wizardStepThree.component'
import {ConfigurationData} from '../classes/configurationData'
import {Report} from '../classes/report'
import {ChartType} from '../classes/chartType'
import {WizardFactory} from '../services/WizardFactory.service'
@Component({
selector: 'wizardMain',
templateUrl: '../../partials/_wizardMain.html',
directives: [WizardStepOneComponent
, WizardStepTwoComponent
, WizardStepThreeComponent],
providers: [Report, ChartType]
})
export class WizardMainComponent{
configurationData: ConfigurationData;
report: Report;
chartType: ChartType;
step1Show:boolean;
step2Show:boolean;
step3Show:boolean;
step4Show:boolean;
configMainShow:boolean;
configSQLServerShow:boolean;
configMySQLShow:boolean;
configHadoopShow:boolean;
configNoSQLShow:boolean;
constructor(public _report: Report
,public _chartType: ChartType){
this.report = _report;
this.chartType = _chartType;
this.hideAll();
this.loadStep(1);
}
hideAll(){
this.step1Show = false;
this.step2Show = false;
this.step3Show = false;
this.step4Show = false;
this.configMainShow = false;
this.configSQLServerShow = false;
this.configMySQLShow = false;
this.configHadoopShow = false;
this.configNoSQLShow = false;
}
loadAdminPanel(){
}
loadMainPanel(){
}
loadStep(stepNumber){
switch(stepNumber)
{
case 1:
{
this.step1Show = true;
this.step2Show = false;
this.step3Show = false;
this.step4Show = false;
this.configMainShow = false;
this.configSQLServerShow = false;
this.configMySQLShow = false;
this.configHadoopShow = false;
this.configNoSQLShow = false;
break;
}
case 2:
{
this.step1Show = false;
this.step2Show = true;
this.step3Show = false;
this.step4Show = false;
this.configMainShow = false;
this.configSQLServerShow = false;
this.configMySQLShow = false;
this.configHadoopShow = false;
this.configNoSQLShow = false;
break;
}
case 3:
{
this.step1Show = false;
this.step2Show = false;
this.step3Show = true;
this.step4Show = false;
this.configMainShow = false;
this.configSQLServerShow = false;
this.configMySQLShow = false;
this.configHadoopShow = false;
this.configNoSQLShow = false;
break;
}
case 4:
{
this.step1Show = false;
this.step2Show = false;
this.step3Show = false;
this.step4Show = true;
this.configMainShow = false;
this.configSQLServerShow = false;
this.configMySQLShow = false;
this.configHadoopShow = false;
this.configNoSQLShow = false;
break;
}
}
}
setConfigurationData(ConfigData: ConfigurationData){
this.configurationData = ConfigData;
}
setReportName(ReportName: string){
this.report.ReportName = ReportName;
this.loadStep(2);
}
setChartType(ChartTypeID: number){
this.chartType.ChartTypeID = ChartTypeID;
WizardFactory.getColumnProperties(this.configurationData).then((data) => {
console.log("SQL Server Response: " + data);
});
this.loadStep(3);
}
setXAxis(XAxis: string){
this.configurationData.XAxis = XAxis;
}
setYAxis(YAxis: string){
this.configurationData.YAxis = YAxis;
this.loadStep(4);
}
}
这里到工厂就好了:
import {$http} from './xhr-factory.service';
import {ConfigurationData} from '../classes/configurationData';
export const WizardFactory = {
getColumnProperties: function (currentConfig) {
console.log("Current Config in Factory: " + JSON.stringify(currentConfig));
return $http.post('/api/getColumnProperties', currentConfig);
}
}
和我的XHR处理程序:
export const $http = {
get: function(url: string) {
return _sendRequest(url, null, 'GET');
},
post: function(url: string, payload: any){
return _sendRequest(url, payload, 'POST');
},
put: function(url: string, payload: any){
return _sendRequest(url, payload, 'PUT');
},
delete: function(url: string, payload: any){
return _sendRequest(url, null, 'DELETE');
}
}
function _sendRequest(url: string, payLoad: any, type: string): Promise<JSON> {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open(type, url);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.onload = function() {
if (req.status == 200) {
console.log("Resolved");
resolve(JSON.parse(req.response));
} else {
reject(JSON.parse(req.response));
}
};
req.onerror = function() {
reject(JSON.parse(req.response));
};
if (payLoad) {
req.send(JSON.stringify(payLoad));
} else {
req.send(null);
}
});
}
但它不会达到我定义的路线;我现在已经操纵了大约100次试图使语法正确:
var express = require('express');
var wizardRouter = express.Router();
var sql = require('mssql');
var sqlReturnDefinitionQuery = "SET NO_BROWSETABLE ON; \
SET FMTONLY ON; \
EXEC {0}; \
SET FMTONLY OFF; \
SET NO_BROWSETABLE OFF";
/*Get Stored Procedure Schema*/
wizardRouter.post('/getColumnProperties', function (req, res, next) {
console.log("In router");
_currentConfig = JSON.parse(req.params.currentConfig);
console.log("Current Config in Router: " + req.params.currentConfig);
var config = {
user: _currentConfig.SQLServerUserName,
password: _currentConfig.SQLServerPassword,
server: _currentConfig.SQLServerHostName,
database: _currentConfig.SQLServerDBName
};
var finalReturnDefinitionQuery = sqlReturnDefinitionQuery.replace("{0}", _currentConfig.StoredProcedureName);
sql.connect(config, function () {
if(err) console.log(err);
var request = new sql.Request();
request.query(finalReturnDefinitionQuery, function(err, recordset){
if(err) console.log(err);
res.send(recordset);
});
});
});
module.exports = wizardRouter;
最后这是我的节点服务器文件:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var wizard = require('./routes/wizard');
var app = express();
// view engine setup
app.set('/', path.join(__dirname, 'partials'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use('/js', express.static(__dirname + '/js'));
app.use('/app', express.static(__dirname + '/app'));
app.use('/content', express.static(__dirname + '/content'));
app.use('/node_modules', express.static(path.join(__dirname, '/node_modules')));
app.use('/partials', express.static(path.join(__dirname, '/partials')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/api/', wizard);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var server = app.listen(1557, function () {
var host = 'localhost';
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
module.exports = app;
非常感谢任何帮助;这让我疯了。
答案 0 :(得分:1)
因此,我认为您的req.onload
函数失败,因为从服务器返回的数据是无效的JSON。引发错误的是JSON.parse(req.response)
。
我在您的服务器代码中注意到了该路由,您没有将字符串化数据发送回Angular应用。尝试将res.send(recordset);
设置为res.send(JSON.stringify(recordset));