Node.js AJAX删除403禁止

时间:2017-08-21 23:56:11

标签: javascript jquery node.js ajax

我尝试创建从服务器删除图像的方法。现在我只想处理DELETE请求并在控制台上显示文件路径... 服务器无法处理我的请求并发送:

  

jquery.min.js:4 DELETE http://localhost:3000/api/imagesbg/wedding-stock-2.jpg 403(禁止)

我做错了什么?

阵线(handlebars.js)

{{#each images}}
  <div class="row">
    {{#each this}}
        <div class="col-sm-4">
            <img src="/images/background-slider/{{this}}" class="img-responsive img-thumbnail" alt="{{this}}">
            <button type="button" class="btn btn-danger pull-right imgBgDel" file-name="{{this}}" >
                Delete
            </button>
        </div>
   {{/each}}
  </div></br>
{{/each}}

脚本

$(function(){
  $('.delete-msg').hide();
  var url;
  $(".imgBgDel").on("click", function(){
      var url = 'http://localhost:3000/api/imagesbg/' + $(this).attr('file-name');
      var allObj = $(this).parent();

      $.ajax({
        url: url,
        type: 'DELETE',
        success: function(result) {
            allObj.remove();
            $('.delete-msg').slideToggle();
            setTimeout(function() {$('.delete-msg').slideToggle();}, 3000);
        },
        error: function(status, xhr) {
            console.log(status);
            alert("An error occured: " + xhr.status + " " + xhr.statusText + " + " + status);
        }
     });
  });
});

index.js

router.delete('/api/imagesbg/:id', isAdmin, function(req, res, next){
  var filePath = '/images/background-slider/' + req.params.id;
  console.log(filePath);
}); //isAdmin check if logged user is admin

完整的app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var fs = require('fs');

var validator = require('express-validator');

var MongoStore = require('connect-mongo')(session);


var index = require('./routes/index');
var userRoutes = require('./routes/user');
var adminRoutes = require('./routes/admin');


var app = express();
var options = {
  user: 'xxx',
  pass: 'xxx'
};

mongoose.connect('mongodb://xxx', options);

require('./config/passport');

// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}) );
app.set('view engine', '.hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({
  secret: 'xxx',
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({
    mongooseConnection: mongoose.connection
  }),
  cookie: {
    maxAge: 180 * 60 * 1000 //how long session lives 180 minutes
  }
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

//bootstrap and jquery
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap


app.use(function(req, res, next){
    res.locals.login = req.isAuthenticated();
    res.locals.adminLogin = (req.isAuthenticated()&&req.user.admin);
    res.locals.session = req.session;
    next();
});


app.use('/admin', adminRoutes);
app.use('/user', userRoutes);
app.use('/', index);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

和完整的index.js

var express = require('express');
var router = express.Router();
var BlogPost = require('../models/blogPost');
var csrf = require('csurf');
var passport = require('passport');
var fs = require('fs');




var csrfProtection = csrf();
router.use(csrfProtection);

router.get('/landing-edit', isAdmin, function(req, res, next){
var messages = req.flash('error');
fs.readdir('public/images/background-slider', function(err, files){
        if(err){
            console.log(err);
        }
        var arrTmp = [];
        var images = [];
        for(var i in files){
            if(arrTmp.length == 3){
                images.push(arrTmp);
                arrTmp = [];
            }
            arrTmp.push(files[i]);
        }
        if(arrTmp)
            images.push(arrTmp);
        console.log(images);

        res.render('admin/landing-bg-admin', {messages: messages, hasErrors: messages.length>0, images: images});
    });


});

router.delete('/api/imagesbg/:id', isAdmin, function(req, res, next){
    var filePath = '/images/background-slider/' + req.params.id;
    console.log(filePath);
    ///res.send(filePath);
});





module.exports = router;

function isAdmin(req, res, next){
    if(req.isAuthenticated() && req.user.admin){
        return next();
    }
    res.redirect('/');
}

3 个答案:

答案 0 :(得分:0)

我之前有类似的东西。根本原因通常是,当您发送与$.ajax一样的XHR请求时,默认情况下请求不包含凭据。由于您使用了护照进行身份验证,当请求在没有凭据的情况下转到您的服务器时,护照会在它到达您的删除路由处理程序之前停止并返回403。

我还没有为$.ajax解决这个问题,我使用了fetch API,但尝试添加:

xhrFields: {
     withCredentials: true
}

$.ajax来电。如果这不起作用,请尝试添加:

username: "yourname"
password: "yourpass"

我敢打赌,根本原因是您的请求不会发送您的凭据。

答案 1 :(得分:0)

我不知道您的服务器是否使用CORS。见https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS。检查页面上的简单请求标题。

如果您的服务器使用CORS,则不允许您执行DELETE请求,因为从其他应答护照中看到的可能不是问题。 我建议你做的是尝试将ajax DELETE请求更改为POST请求并从那里移动。

使用type: 'POST',您仍然可以删除图片,使用POST的正确功能,403: Forbidden可能不会出现。

答案 2 :(得分:0)

router.get('/api/imagesbg/:id', isAdmin, (req, res, next)=>{
  const query = {_id: req.params.id}
  if(!ObjectID.isValid(req.params.id)){
    return res.render('error', {message: "Error didn't found the given id"});
  }
  Blogpost.findOneAndRemove({
    _id: query,
    _creator: req.user._id // if you have creator id else remove it
  }).then((post)=>{
    if(!post){
      return res.status(400).send();
    }
    res.redirect('/home');
  }).catch((e)=>{
    res.status(400).send();
  });
});

尝试此操作并删除脚本文件中的ajax代码,然后尝试获取请求,然后删除数据。