我正在做一个本机应用程序, 我注册了一个执行API调用的headlessJS。 API通过邮递员工作正常,但在通过应用程序发出请求时,出现错误 这是我在请求的应用程序中的代码
axios({
method: 'post',
url: '13.126.71.152:3000/checkin',
data: {
location,
name: naming
}
}).then((res) => {
return res;
}).then((resp) => {
console.log(resp);
}).catch((error) => {
console.log(error);
});
我收到以下错误
Error: Network Error
at createError (20ecc2c2-cb5e-4e50-9…-5e92abf47ba8:80610)
at XMLHttpRequest.handleError (20ecc2c2-cb5e-4e50-
9…-5e92abf47ba8:80518)
at XMLHttpRequest.dispatchEvent (20ecc2c2-cb5e-4e50-9…-5e92abf47ba8:17922)
at XMLHttpRequest.setReadyState (20ecc2c2-cb5e-4e50-9…-5e92abf47ba8:17677)
at XMLHttpRequest.__didCompleteResponse (20ecc2c2-cb5e-4e50-9…-5e92abf47ba8:17504)
at 20ecc2c2-cb5e-4e50-9…-5e92abf47ba8:17614
at RCTDeviceEventEmitter.emit (20ecc2c2-cb5e-4e50-9…f-5e92abf47ba8:3478)
at MessageQueue.__callFunction (20ecc2c2-cb5e-4e50-9…f-5e92abf47ba8:2384)
at 20ecc2c2-cb5e-4e50-9…f-5e92abf47ba8:2154
at MessageQueue.__guardSafe (20ecc2c2-cb5e-4e50-9…f-5e92abf47ba8:2346)
我在节点js上的服务器代码 我的server.js代码
var express = require('express');
app = express();
const cors = require('cors');
const path = require('path');
port = process.env.PORT || 3000,
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Set public folder
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,x-auth");
res.header('Access-Control-Expose-Headers', 'x-auth');
next();
});
var routes = require('./api/routes/MetroRoutes'); //importing
route
routes(app); //register the route
app.listen(port);
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'})
});
console.log('metro RESTful API server started on: ' + port);
我的控制器代码:./api/controllers/MetroController
exports.checkInDetected = function(req,res) {
console.log(req.body);
pusher.trigger( 'ieacon-calc', 'checkInDetected', {
"name": req.body.name,
"location": req.body.location
});
res.json({ message: 'checkInDetected' });
}
exports.checkOutDetected = function(req,res) {
pusher.trigger( 'ieacon-calc', 'checkOutDetected', {
"name": req.body.name,
"location": req.body.location
});
res.json({ message: 'checkOutDetected' });
}
这是我的路线档案:./api/routes/MetroRoutes
module.exports = function(app) {
var todoList = require('../controllers/MetroController');
// todoList Routes
app.route('/checkin')
.post(todoList.checkInDetected)
app.route('/checkout')
.post(todoList.checkOutDetected);
};
答案 0 :(得分:0)
添加
app.use(cors());
它应该有用。
如果使用节点创建API,请始终使用cors。 阅读https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS以了解CORS