LoginSignup
0
0

More than 3 years have passed since last update.

three.js の examplesをnode.jsで動かす

Last updated at Posted at 2021-04-17

node.jsでthree,jsのサンプルを動かそうとすると
SyntaxError: Unexpected token < in JSON at position 0
だったりデータが取ってこれないことがありました。
原因はContent-Typeやencodingが適切に設定されていないことのようでしたので、

$ npm install mime-types

でモジュールを追加し(必要があれば)、

server.js
const mime = require('mime-types');
const port = 8080;
var http = require('http');
var fs   = require('fs');
var http_server = new http.createServer(function(req, res) {
  var url = decodeURI('.'+req.url);
  if(!fs.existsSync(url)) {
    console.log(url+" not found");
  }else{
    let type = mime.lookup(url);
    type = type ? type : "application/etc";
    //console.log('>>'+'.'+url+':'+type);
    let encoding = type.hasOwnProperty('includes') ? (type.includes('text') ? 'UTF-8' : null) : null;
    let data = fs.readFileSync(url,encoding);
    res.writeHead(200, {'Content-Type': type});
    res.end(data);
}
}).listen(port);
console.log('Check http://localhost:'+port+'/ on brouser.');

を作成し

node server.js

とすることで解決できました。

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0