【问题标题】:Why do my rest endpoints not work on my node server?为什么我的休息端点不能在我的节点服务器上工作?
【发布时间】:2016-09-18 20:28:53
【问题描述】:

我的 index.js 文件如下所示:

var http = require('http');
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser')

var app = express();
var currentVideo = 'https://www.youtube.com/embed/9Q-ovNuireY';

// parse application/json
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(res) {
  console.log("sup");
});

app.get('/currentVideo', function(req, res) {
  res.send(200, {youtubeSrc: currentVideo});
});

http.createServer(app).listen(process.env.PORT ||3000, function() {
  console.log('Example app listening on port 3000!');
});

我的公共静态页面加载完毕,我的服务器正常启动并打印出示例应用程序日志。当我尝试达到我的 get 端点时,虽然它不起作用。我一直在打 http://localhost:{port}/currentVideo 并得到 404。

【问题讨论】:

  • http://localhost:{port}/currentVideo{port} 正确替换了吗?你用什么 HTTP 客户端测试过?
  • 是的,端口是动态的,但它是正确的。我只是在浏览器中测试了它。
  • @Grammin 请在此处发布您从公共页面到 API 的 javascript 调用。

标签: javascript node.js rest express


【解决方案1】:

我复制了您的代码并使用 curl 在本地对其进行了测试。该请求工作正常。

你能分享你的公共页面吗?当您尝试加载数据时,Chrome 开发者工具控制台中是否显示任何日志?

curl -v http://localhost:3000/currentVideo
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /currentVideo HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.47.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 58
< ETag: W/"3a-FMsS5hMXa1tcIFnGeYHinQ"
< Date: Sun, 18 Sep 2016 20:34:04 GMT
< Connection: keep-alive
< 
* Connection #0 to host localhost left intact
{"youtubeSrc":"https://www.youtube.com/embed/9Q-ovNuireY"}

【讨论】:

  • 恐怕这更像是一个评论而不是一个实际的答案。
  • 抱歉,我是 StackOverflow 的新手,我只是想提供帮助。
  • 浏览器日志看起来不错,它们的端点只给我一个 404。我的 html 文件加载如下:localhost:63342/last/app/public/index.html。在我的 package.json 中,我有类似:“main”:“app/index.js”,我不知道这是否重要?
  • 别担心。只需删除此答案并对上述问题发表评论(例如,您可以将该控制台日志包含在 pastebin 中并将其链接)。
猜你喜欢
  • 2020-12-10
  • 2015-09-24
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 2011-01-06
  • 2020-09-25
  • 2014-07-13
  • 1970-01-01
相关资源
最近更新 更多