2012-09-29 3 views
23

대학 과정에서 node.js 및 json 객체로 작업하기 시작했습니다. 이번 주 과제 중 하나는 몇 개의 json 객체를 생성하고 객체의 일부를 html 페이지로 추출하는 것이 었습니다. 이 작업을 수행하는 방법에 대해 잘 알고 있다고 생각했지만 노드를 시작하려고 할 때 오류가 발생했습니다. colleges 객체와 구문 분석 문을 제거하면 노드가 올바르게 실행됩니다.JSON + Node.js - 예기치 않은 토큰 o

undefined:1 
[object Object],[object Object],[object Object],[object Object],[object Object 
^ 
SyntaxError: Unexpected token o 
at Object.parse (native) 
at Object.<anonymous> (/home/ubuntu/node_stuff/node_json/requestHandlers.js:13:20) 
at Module._compile (module.js:449:26) 
at Object.Module._extensions..js (module.js:467:10) 
at Module.load (module.js:356:32) 
at Function.Module._load (module.js:312:12) 
at Module.require (module.js:362:17) 
at require (module.js:378:17) 
at Object.<anonymous> (/home/ubuntu/node_stuff/node_json/index.js:3:23) 
at Module._compile (module.js:449:26) 

그리고 여기에 내가 함께 일하고 코드입니다 : 여기

내가 "노드하는 index.js"를 실행할 때 내가 오류입니다.

var querystring = require("querystring"), 
fs = require("fs"), 
formidable = require("formidable"); 

var colleges = [ 
{"name":"A-B Tech","street":"340 Victoria Road","city":"Asheville","state":"NC","zip":"28801","phone":"828-254-1921"}, 
{"name":"UNC Asheville","street":"1 University Heights","city":"Asheville","state":"NC","zip":"28804","phone":"828-251-6600"}, 
{"name":"UNC Charlotte","street":"9201 University City Blvd","city":"Charlotte","state":"NC","zip":"28223","phone":"704-687-8622"}, 
{"name":"Western Carolina","street":"North Carolina 107","city":"Cullowhee","state":"NC","zip":"28723","phone":"877-928-4968"}, 
{"name":"NC State","street":"2200 Hillsborough","city":"Raleigh","state":"NC","zip":"27695","phone":"919-515-2011"} 
]; 

var college = JSON.parse(colleges); 

function abtech(response) { 
console.log("Request handler 'abtech' was called."); 

var body = '<html>'+ 
'<head>'+ 
'<meta http-equiv="Content-Type" '+ 
'content="text/html; charset=UTF-8" />'+ 
'</head>'+ 
'<body>'+ 
'<ul>'+ 
'<li>' + college[0].name + '</li>'+ 
'<li>' + college[0].street + '</li>'+ 
'<li>' + college[0].city + ' ' + college[0].state + ' ' + college[0].zip + '</li>'+ 
'<li>' + college[0].phone + '</li>'+ 
'</ul>'+ 
'</body>'+ 
'</html>'; 

response.writeHead(200, {"Content-Type": "text/html"}); 
response.write(body); 
response.end(); 
} 

function unca(response) { 
console.log("Request handler 'abtech' was called."); 

var body = '<html>'+ 
'<head>'+ 
'<meta http-equiv="Content-Type" '+ 
'content="text/html; charset=UTF-8" />'+ 
'</head>'+ 
'<body>'+ 
'<ul>'+ 
'<li></li>'+ 
'<li></li>'+ 
'<li></li>'+ 
'<li></li>'+ 
'</ul>'+ 
'</body>'+ 
'</html>'; 

response.writeHead(200, {"Content-Type": "text/html"}); 
response.write(body); 
response.end(); 
} 

function home(response) { 
console.log("Request handler 'home' was called."); 

var body = '<html>'+ 
'<head>'+ 
'<meta http-equiv="Content-Type" '+ 
'content="text/html; charset=UTF-8" />'+ 
'</head>'+ 
'<body>'+ 
'<h1>Welcome to College</h2>'+ 
'<p>Where would you like to visit?</p>'+ 
'<ul>'+ 
'<li><a href="/colleges">Colleges</a></li>'+ 
'<li><a href="/hours">Hours of Operation</a></li>'+ 
'<li><a href="/start">Upload a Photo</a></li>'+ 
'<li><a href="/show">View Gallery</a></li>'+ 
'</ul>'+ 
'</body>'+ 
'</html>'; 

response.writeHead(200, {"Content-Type": "text/html"}); 
response.write(body); 
response.end(); 
} 

function colleges(response) { 
console.log("Request handler 'colleges' was called."); 

var body = '<html>'+ 
'<head>'+ 
'<meta http-equiv="Content-Type" '+ 
'content="text/html; charset=UTF-8" />'+ 
'</head>'+ 
'<body>'+ 
'<h1>Colleges</h2>'+ 
'<ul>'+ 
'<li><a href="/abtech">A-B Tech</a></li>'+ 
'<li><a href="/unca">UNC Asheville</a></li>'+ 
'<li><a href="/uncc">UNC Charlotte</a></li>'+ 
'<li><a href="/wcu">Western Carolina</a></li>'+ 
'<li><a href="/ncsu">NC State</a></li>'+ 
'</ul>'+ 
'</body>'+ 
'</html>'; 

response.writeHead(200, {"Content-Type": "text/html"}); 
response.write(body); 
response.end(); 
} 

function hours(response) { 
console.log("Request handler 'gallery' was called."); 

var body = '<html>'+ 
'<head>'+ 
'<meta http-equiv="Content-Type" '+ 
'content="text/html; charset=UTF-8" />'+ 
'</head>'+ 
'<body>'+ 
'<h1>Hours of Operation</h2>'+ 
'<table>'+ 
'<tr><td>Monday - Thursday</td><td>9 a.m. - 7 p.m.</td></tr>'+ 
'<tr><td>Friday</td><td>9 a.m. - 5 p.m.</td></tr>'+ 
'<tr><td>Saturday</td><td>9 a.m. - 12 p.m.</td></tr>'+ 
'</table>'+ 
'</body>'+ 
'</html>'; 

response.writeHead(200, {"Content-Type": "text/html"}); 
response.write(body); 
response.end(); 
} 


function start(response) { 
console.log("Request handler 'start' was called."); 

var body = '<html>'+ 
'<head>'+ 
'<meta http-equiv="Content-Type" '+ 
'content="text/html; charset=UTF-8" />'+ 
'</head>'+ 
'<body>'+ 
'<h1>Upload a file</h2>'+ 
'<p>It will be shown on the /show url after</p>'+ 
'<form action="/upload" enctype="multipart/form-data" '+ 
'method="post">'+ 
'<input type="file" name="upload" multiple="multiple">'+ 
'<input type="submit" value="Upload file" />'+ 
'</form>'+ 
'</body>'+ 
'</html>'; 

response.writeHead(200, {"Content-Type": "text/html"}); 
response.write(body); 
response.end(); 
} 

function upload(response, request) { 
console.log("Request handler 'upload' was called."); 

var form = new formidable.IncomingForm(); 
console.log("about to parse"); 
form.parse(request, function(error, fields, files) { 
console.log("parsing done"); 

/* Possible error on Windows systems: 
    tried to rename to an already existing file */ 
fs.rename(files.upload.path, "/home/ubuntu/node_stuff/node_assignment/test.jpg", function(err) { 
    if (err) { 
    fs.unlink("/home/ubuntu/node_stuff/node_assignment/test.jpg") 
    fs.rename(files.upload.path, "/home/ubuntu/node_stuff/node_assignment/test.jpg"); 
    } 
}); 
response.writeHead(200, {"Content-Type": "text/html"}); 
response.write("received image:<br/>"); 
response.write("<img src='/show' />"); 
response.end(); 
}); 
} 

function show(response) { 
console.log("Request handler 'show' was called."); 
fs.readFile("/home/ubuntu/node_stuff/node_assignment/test.jpg", "binary", function(error, file) { 
if(error) { 
    response.writeHead(500, {"Content-Type": "text/plain"}); 
    response.write(error + "\n"); 
    response.end(); 
} else { 
    response.writeHead(200, {"Content-Type": "image/jpg"}); 
    response.write(file, "binary"); 
    response.end(); 
} 
}); 
} 

exports.start = start; 
exports.upload = upload; 
exports.show = show; 
exports.home = home; 
exports.colleges = colleges; 
exports.hours = hours; 
exports.abtech = abtech; 

내가 잘못하고있는 것에 대한 암시는 매우 감사하겠습니다. 내 강사는 주말에 잡기가 힘들어. 그래서 나는 돌변 할 다른 곳이 없어. 고맙습니다.

+1

좋은 생각, 코드의 나머지 부분

, 당신은 코드를 좀 더 소형을 쓸 수 Express 또는 Zappa를 살펴 할 수 있습니다; 당신이 일하는 것을보기 위해서. 많은 프레임 워크 (Express, Restify 등)가 JSON 구문 분석을 처리합니다. 특히 HTTP 요청을 통해 JSON을 파싱하는 경우에 유용합니다. –

답변

28

colleges 변수는 이미 유효한 JavaScript 개체입니다. 거기에 JSON.parse을 사용할 필요가 없습니다.

JSON.parse은 첫 번째 인수로 String이 필요하지만 Object을 제공합니다. 따라서 오류 메시지에 표시되는 것과 같은 모양으로 표시됩니다 (String).) 대해서 typeof (yourVar를 사용하는) 항상

+0

Tharabas 감사합니다. 구문 분석 문이 필요 없다는 것을 인식하지 못했습니다. 수업에서 시범을 보였고 지금 사용하고 있습니다. 곧 Express와 MongoDB를 진행할 것입니다. –