gpt4 book ai didi

javascript - AngularJS 通过 localhost 向 ExpressJS 发出请求

转载 作者:行者123 更新时间:2023-12-01 03:56:32 26 4
gpt4 key购买 nike

我使用 AngularJS x ExpressJS 创建了一个 Web 应用程序,其中 app.js 的 GET "/"呈现应用程序的 index.html

例如,我在 app.js 上有 GET /test-data 并尝试通过 localhost:port/test 从 AngularJS 获取这些测试数据-数据。虽然这在我的测试环境中有效,但我总是必须将生产上的请求 URL 更改为生产的 REST。

有什么方法可以防止在部署期间编辑 URL 时出现上述问题吗?

示例代码:

(app.js)

var express = require("express");
var app = express();
var request = require("request");
var port = 3000;
var bodyParser = require("body-parser");

app.use(express.static(__dirname));

app.use(bodyParser.json());

app.get("/", function(request, response) {
response.sendFile(__dirname + "/index.html");
});

app.get("/test-data", function(req, res, next) {
var returnValue = [
{
username : "MAIK",
fullname : "Michael"
},
{
username : "CLARK",
fullname : "Clark"
},
{
username : "ROLLY",
fullname : "Roland"
},
{
username : "FLOYDIE",
fullname : "Floyd"
},
{
username : "ZOE",
fullname : "Zoe"
}
];

res.send(returnValue);

});

app.listen(port, function() {
console.log("Listening to port " + port + "...");
});

(MySampleService.js)

.service("MySampleService", function($http) {

this.sampleURL = "localhost:3000";

this.getTestData= function(){
return $http
(
{
method : "GET",
url : "http://" + this.sampleURL + "/test-data
}
);
};
});

最佳答案

对于您的 URL,只需使用 /test-data。该请求自动知道使用托管应用程序的同一端口。

关于javascript - AngularJS 通过 localhost 向 ExpressJS 发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42622261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com