【发布时间】:2017-06-14 09:55:33
【问题描述】:
我正在使用 NodeJs 做一个大学项目,但在本地测试它时遇到了一些麻烦。
这就是问题所在: 我有一个 GET API "/api/services/names" 并且 NodeJS 服务器在端口 8080 上运行。
如果我通过将 URL 放在 Chrome 栏 ("http://localhost:8080/api/services/names") 中使用 Postmanor 测试 API,它可以正常工作并且我可以得到我的响应。
问题是,如果我在本地网站上使用 fetch() 在这个函数中测试它:
function fetchServicesNames(){
fetch('/api/services/names')
.then(function(response){
return response.json();
})
.then(function(data){
data.map(addServiceLink);
});
}
Javascript 控制台给了我这个错误:
Failed to load resource: the server responded with a status of 404 (Not Found)
我注意到,当我悬停控制台错误时,它显示的请求字符串“http://localhost/api/services/names”没有端口。但我认为这不是问题,因为当我在 Heroku 平台上部署应用程序时,它工作正常......问题只是在 localhost 中(我正在使用 Mac OSX 10.10.2 的 2010 年中期 macbook pro) .
感谢您的帮助,提前感谢您。
编辑: 根据要求,我在这里添加服务器代码
// server.js for Hypermedia Application project.
// BASE SETUP
//============================================================
// call packages
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
// we use body-parser, so we need to be able to read data either from
// GET and POST:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// setting the application port to listen
var serverPort = process.env.PORT || 5000;
// --- database connection omitted ---
// API ROUTES
// ================================================================
// first of all: get the Router
var router = express.Router();
/**
* Services names
* /api/services/names - get - get all services ids and names
*/
router.route('/services/names')
.get(function (req, res) {
Service.find({}, 'id name', function (err, services) {
if (err)
res.send(err);
res.json(services);
});
});
// --- Other APIs omitted ---
// REGISTER ROUTES:
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
//===================================================================
app.set("port", serverPort);
app.listen(serverPort, function() {
console.log(`Your app is ready at port ${serverPort}`);
});
【问题讨论】:
-
向我们展示服务器代码。
-
这是一个正常的浏览器工作流程,如果你正在获取
/api,浏览器将获取打开的url +/api/,只需获取完整的地址,如fetch('localhost:8080/api...'),如果一切都写好了,那么在生产中就差不多了很好,您将拥有某种类型的 API url 常量,并将使用此常量获取它。 -
它给了我
script.js:47 Fetch API cannot load localhost:5000/api/services/names. URL scheme must be "http" or "https" for CORS request.端口因我的团队选择而改变 -
批准我的回答
-
请将解决方案作为答案发布,而不是作为问题的更新。这是为了帮助未来的访客并避免混淆。谢谢。
标签: javascript node.js