用 node.js 做一个 api

Make an api with node.js

我尝试使用 node.js (+express) 构建一个 api。 Firefox 显示它但是当我尝试使用 p5.js 中的 loadJSON 加载它时它显示奇怪的错误。 这是 node.js 代码(基于此:modulus: create api with node.js ):

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 日。

我认为您在从浏览器访问 API 时遇到了跨源问题。

您在浏览器控制台中看到什么错误?如果是这样,您可以通过允许在您的服务器上进行跨源访问或从同一网络服务器加载您的网页(这将使您的 api 具有相同的来源)来修复它。