【问题标题】:Nodejs local API does not workNodejs 本地 API 不起作用
【发布时间】: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


【解决方案1】:

在您添加的服务器页面上

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

在您的 API 之前

它可能对 CORS 有帮助

【讨论】:

    【解决方案2】:

    亲爱的我建议你写总路径像

    http://localhost:<your port number>/api/services/names
    

    在 fetch() 里面检查一次

    我也试过了,我成功了

    【讨论】:

    • 我试过了,它给了我这个错误:Fetch API cannot load http://localhost:5000/api/services/names. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.我不知道它会是什么
    • @DavideCremona 该错误消息非常具有描述性。您正在发出跨域请求,而服务器通过省略 Access-Control-Allow-Origin 标头而不允许跨域请求。
    • @KevinB 是的,我知道,但如果我在网络浏览器 localhost:5000/api/services/names 中写入,而没有 http:// 部分,它就可以工作。我不明白为什么如果我删除端口它不起作用(在部署的应用程序中它起作用)
    • 因为如果您删除端口,您将访问不同的来源。从而使它成为一个跨域请求。
    • 在您的服务器页面上保留app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); 它可能对 CORS 有帮助
    【解决方案3】:

    你好尝试修改fetch('http://'+window.location.host+':8080/api/services/...)这样的行

    【讨论】:

    • window.location.host 将仅回显当前服务器主机。像localhost。所以让我们也连接端口。像fetch('http://'+window.location.host+':8080/api/services/...)。它会做的伎俩
    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 2023-03-03
    • 2018-07-25
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2019-06-18
    相关资源
    最近更新 更多