0
我正在嘗試創建一個將用於我的前端的API。
我使用ExpressJs
作爲NodeJS
框架的服務器和RethinkDB
作爲數據庫。
我在調用API時遇到問題。在每次API調用之後,始終在控制檯中收到消息。
ExpressJs + RethinkDB創建API
錯誤:Someone asked for the nonwhitelisted file "https://stackoverflow.com/users/". If this should be accessible, add it to the static web assets.
我的入口點server.js
'use strict'
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const helmet = require('helmet');
require('dotenv').config();
const app = express();
app.use(logger('dev'));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(cors());
app.use(helmet());
const users = require('./routes/users');
const connect = require('./lib/connect');
app.use(connect.connect);
app.use('/users', users);
app.use(connect.close);
app.use((error, request, response, next) => {
response.status(error.status || 500);
response.json({
error: error.message
});
});
app.use((request, response, next) => {
let error = new Error('Not Found');
error.status = 404;
response.json(error);
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('App is listening on http://%s:%s', host, port);
});
API路線。在server.js
使用的文件作爲爲const users = require('./routes/users');
app.use('/users', users);
'use strict';
const r = require('rethinkdb');
const router = require('express').Router();
const connect = require('../lib/connect');
router.post('/users',(request, response) => {
let user = Object.assign({},{
'email': request.body.email,
'name': request.body.name,
'password': request.body.password
});
r.db('Planner').table('users')
.insert(user)
.run(request._rdb)
.then(cursor => cursor.toArray())
.then(result => {
response.send(result)
})
.catch(error => response.send(error));
});
router.get('/users', (request, response) => {
r.db('auth').table('users')
.run(request._rdb)
.then(cursor => cursor.toArray())
.then(result => {
response.send(result);
})
.catch(error => response.send(error));
});
router.put('/users/:user_id', (request, response) => {
let user_id = request.params.user_id;
r.db('auth').table('users')
.get(user_id)
.update({
'email': request.body.email,
'name': request.body.name
})
.run(request._rdb)
.then(cursor => cursor.toArray())
.then(result => {
response.send(result);
})
.catch(error => response.send(error));
});
router.delete('/users/:user_id', (request, response) => {
let user_id = request.params.user_id;
r.db('auth').table('users')
.get(user_id)
.delete()
.run(request._rdb)
.then(cursor => cursor.toArray())
.then(result => {
response.send(result);
})
.catch(error => response.send(error));
});
module.exports = router;