2016-12-30 44 views
0

我嘗試使用node.js(+ express)構建api。 Firefox顯示它,但是當我嘗試從p5.js中加載loadJSON時,它顯示奇怪的錯誤。 這裏是Node.js的代碼(在此基礎上:modulus: create api with node.js):使用node.js製作api

express = require("express"); 
app = express(); 
app.listen(4000); 

var quotes = [ 
    { author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"}, 
    { author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"}, 
    { author : 'Unknown', text : "Even the greatest was once a beginner. Don't be afraid to take that first step."}, 
    { author : 'Neale Donald Walsch', text : "You are afraid to die, and you're afraid to live. What a way to exist."} 
]; 


app.get('/', function(req, res){ 
    res.json(quotes); 
}) 

p5.js:

function setup() { 
    loadJSON("http://localhost:4000/", getJson, error1); 
} 

function getJson(data) { 
    console.log("json get"); 
    console.log(data) 
} 

function error1(err) { 
    console.log("Error: "); 
    console.log(err); 
} 

錯誤:

"Error: " 
{ 
    "statusText": "", 
    "status": 0, 
    "responseURL": "", 
    "response": "", 
    "responseType": "", 
    "responseXML": null, 
    "responseText": "", 
    "upload": { 
    "ontimeout": null, 
    "onprogress": null, 
    "onloadstart": null, 
    "onloadend": null, 
    "onload": null, 
    "onerror": null, 
    "onabort": null 
    }, 
    "withCredentials": false, 
    "readyState": 4, 
    "timeout": 0, 
    "ontimeout": null, 
    "onprogress": null, 
    "onloadstart": null, 
    "onloadend": null, 
    "onload": null, 
    "onerror": null, 
    "onabort": null 
} 

我一直在使用 'JSONP' 嘗試,但它顯示了這一點:

5209: Uncaught TypeError: Cannot read property 'responseText' of undefined 

我有node.js v4.2.2和p5.js v0.5.4 2016年10月1日。

+1

我想你從瀏覽器訪問API時可能會遇到跨源問題。您在瀏覽器控制檯中看到哪些錯誤?如果是這樣,您可以通過允許在服務器上進行跨源訪問或通過從同一個Web服務器加載您的網頁(這將使您的api具有相同的來源)來修復它。 – jfriend00

+0

就像jfriend說的那樣,你需要查看你的JavaScript控制檯和網絡選項卡是否有任何錯誤。此外,你可能想要拿出P5.js的東西,因爲這與問題無關。只需使用基本的JavaScript,人們就會更好地理解你的問題。 –

+0

@ jfriend00我在firefox中運行了p5.js文件,並在控制檯中發現了一個新的錯誤(跨源訪問)。我修好了它。我認爲這應該作爲答案發布。 –

回答

1

我從瀏覽器訪問API時似乎存在跨源問題。

您在瀏覽器控制檯中看到了哪些錯誤?如果是這樣,您可以通過允許在服務器上進行跨源訪問或通過從同一個Web服務器加載您的網頁(這將使您的api具有相同的來源)來修復它。