客户端无法击中自己的服务器端点
我有一个AngularFullStack项目,我试图用下面的代码打我的项目的服务器端点,但问题是调用不是从angular度客户端到nodejs服务器。 由于这是我的第一个项目,我很less不知道可能会出现什么问题,可能会导致这个奇怪的冲突。
客户端:
$http({ method: 'POST', url: '/api/soapAPIs/soapAPI', data: request, headers: { 'Content-Type': 'application/json' } }) .then(function(response) { console.log("response from server is: ", response); }) .catch(function(error) { console.log("error in calling server is: ", error); });
我已经在服务器端安装了CORS,并在app.js中写下了下面的代码,但仍然无效。
服务器App.js
// Setup server var app = express(); var cors = require('cors'); //add cors to do the cross site requests app.use(cors());
服务器端点代码:
export function soapAPI(req, res) { console.log("SERVER SIDE ", req.body); res.status(statusCode).json({"status":"success"}); res.send(); }
以下是问题:
-
如果我尝试像这样
/api/soapAPIs/soapAPI
命中nodejs端点,则浏览器显示pending
请求,并且永远不会到服务器。 -
当我为
http:localhost:9000/api/soapAPIs/soapAPI
添加端点的完整分类url时,它会碰到端点,但是客户端永远不会收到来自服务器的响应。 我不想在客户端提供完整的分类URL,原因很明显。
我该如何解决这个问题? 请让我知道如果你需要任何其他的代码/信息。
编辑:
通过使用完整的分类path,服务器端点被击中,但其响应从未被客户端接收。 我在浏览器中得到这个错误:
Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/things","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}
取消注释以下行:
/*mongoose.connect(config.mongo.uri, config.mongo.options); mongoose.connection.on('error', function(err) { console.error(`MongoDB connection error: ${err}`); process.exit(-1); // eslint-disable-line no-process-exit }); */
基本上这是导致你的控制器不返回任何响应,因为你的mongoose模型被引用,但连接到mongo失败。
你必须使用res.send()
发回请求
app.post('/api/soapAPIs/soapAPI',function(req,res){ console.log("SERVER SIDE ", req.body); res.status(statusCode).json({"status":"success"}}); res.send(); })