cphill
cphill

Reputation: 5914

ExpressJS XMLHttpRequest Routing Error

I have an issue where I am trying to pass my file information in query parameter form to the route that I have set up to upload my AWS file and then return the url. The issue I am running into is that the form is located within the view file accessed with the /create/comment route and prepended to all of my routes is /app. In my XMLHttpRequest I am requesting /app/sign and the file query parameters, but for some reason it keeps prepending this with /app/create or /app/create/app/sign, which is why I have 404 error. Is there a way a specific method to prevent the prepending of /app/create?

Error function at xhr.send();

function sign_request(file, done) {
        var xhr = new XMLHttpRequest();
        console.log(xhr);
        console.log(file);
        xhr.open("GET", "app/sign?file_name=" + file.name + "&file_type=" + file.type);
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                console.log(response);
                done(response);
            }
        };
        xhr.send();
    };

Error Message:

comment:139 GET http://localhost:3000/app/create/app/sign?file_name=File-name.png&file_type=image/png 404 (Not Found)

Here is my route setup:

  var express = require('express');
    var router  = express.Router();
    router.use('/app');
var config = require(path.resolve(__dirname, '..', '..','./config/config.js'));
var models = require('../models/db-index');
var fs = require('fs');
var aws = require('aws-sdk');

    /*====   /SIGN  ====*/

    router.get('/sign', function(req, res){
        aws.config.update({accessKeyId: config.awsAccessKeyId, secretAccessKey: config.awsSecretAccessKey});

        var s3 = new aws.S3()
        var options = {
          Bucket: config.awsBucket,
          Region: 'us-east-1',
          Key: req.query.file_name,
          Expires: 60,
          ContentType: req.query.file_type,
          ACL: 'public-read'
        }

        s3.getSignedUrl('putObject', options, function(err, data){
          if(err) return res.send('Error with S3')

          res.json({
            signed_request: data,
            url: 'https://s3.amazonaws.com/' + S3_BUCKET + '/' + req.query.file_name
          });
        });
    });

    router.get('/create/comment',function(req, res){
            models.DiscoverySource.findAll({
                where: {
                    organizationId: req.user.organizationId
                }, attributes: ['discoverySourceName']
            }).then(function(discoverySource){
                res.render('pages/app/comment-create.hbs',{
                    discoverySource: discoverySource
                });
            });

        });

Form (Accessed at /app/create/comment):

<!DOCTYPE html>
<head>
    {{> app/app-head}}
</head>
<body>
    {{> app/app-navigation}}
    <div class="container">
        <div class="col-md-12">
            <div class="row-form-container">
                <label for="report-link">File Attachment:</label>
                    <input type="file" name="fileAttachment" id="image"> 
                    <img id="preview">
            </div>
    </div>
    <script type="text/javascript">


        function upload(file, signed_request, url, done) {
            var xhr = new XMLHttpRequest();
            xhr.open("PUT", signed_request);
            xhr.setRequestHeader('x-amz-acl', 'public-read');
            xhr.onload = function() {
            if (xhr.status === 200) {
                done();
            };
        };
        xhr.send(file);
        }

    function sign_request(file, done) {
        console.log('work please');
        var xhr = new XMLHttpRequest();
        console.log(xhr);
        console.log(file);
        xhr.open("GET", "app/sign?file_name=" + file.name + "&file_type=" + file.type);
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                console.log(response);
                done(response);
            }
        };
        xhr.send();
    };

    document.getElementById("image").onchange = function() {
        var file = document.getElementById("image").files[0]
        if (!file) return
            sign_request(file, function(response) {
                upload(file, response.signed_request, response.url, function() {
                    document.getElementById("preview").src = response.url
                });
            });
    };
    </script>
</body>

Upvotes: 1

Views: 572

Answers (1)

Zen
Zen

Reputation: 5500

Adding a / before app/sign when you send a request will prevent the prepending of current subpath. Try:

xhr.open("GET", "/app/sign?file_name=" + file.name + "&file_type=" + file.type);

Upvotes: 2

Related Questions