2017-02-14 29 views
1

Я создаю API, и сегодня я интегрировал его с формой HTML. Тем не менее, он просто говорит: «Не может быть POST/newship». Что не так? Мои server.js:API-интерфейс для переноса узлов с использованием Shippo не работает

var express = require('express') 
var app = express() 
var http = require('http'); 
//Shippo shipping wrapper 
var Raven = require('raven'); 
var shippo = require('shippo')('shippo_test_key'); 
const bodyParser = require('body-parser'); 
app.use(bodyParser.urlencoded({extended: true})); 
app.use(bodyParser.json()); 
//Test 

app.get('/', function (req, res) { 
    res.send('Hello World! ' + 'hey') 
}) 
app.post('/newship/', function (req, res) { 

    var addressFrom = { 
     "object_purpose":"PURCHASE", 
     "name": Mr Shippotester, 
     "company":"Shippo", 
     "street1":"215 Clayton St.", 
     "city":"San Francisco", 
     "state":"CA", 
     "zip":"94117", 
     "country":"US", //iso2 country code 
     "phone":"+1 555 341 9393", 
     "email":"[email protected]", 
    }; 

    // example address_to object dict 
    var addressTo = { 
     "object_purpose":"PURCHASE", 
     "name": req.body.fnames + ' ' + req.body.lnames, 
     "company": req.body.company, 
     "street1":req.body.street, 
     "city":req.body.city, 
     "state":req.body.state, 
     "zip":req.body.zipcode, 
     "country": req.body.country, //iso2 country code 
     "phone":"+1 555 341 9393", 
     "email":"[email protected]", 
    }; 

    // parcel object dict 
    var parcelOne = { 
     "length":"5", 
     "width":"5", 
     "height":"5", 
     "distance_unit":"in", 
     "weight":"2", 
     "mass_unit":"lb" 
    }; 


    var shipment = { 
     "object_purpose": "PURCHASE", 
     "address_from": addressFrom, 
     "address_to": addressTo, 
     "parcel": [parcelOne], 
     "submission_type": "DROPOFF" 
    }; 

    shippo.transaction.create({ 
     "shipment": shipment, 
     "servicelevel_token": "dhl_express_domestic_express_doc", 
     "carrier_account": "account_id", 
     "label_file_type": "png" 
    }) 
    .then(function(transaction) { 
     shippo.transaction.list({ 
     "rate": transaction.rate 
     }) 
     .then(function(mpsTransactions) { 
      mpsTransactions.results.forEach(function(mpsTransaction){ 
       if(mpsTransaction.object_status == "SUCCESS") { 
        console.log("Label URL: %s", mpsTransaction.label_url); 
        console.log("Tracking Number: %s", mpsTransaction.tracking_number); 
        console.log("E-Mail: %s", mpsTransaction.object_owner); 
        console.log(mpsTransaction.object_status); 
        res.status(200).send("Label can be found under: " + mpsTransaction.label_url)); 
       } else { 
        // hanlde error transactions 
        console.log("Message: %s", mpsTransactions.messages); 
       } 
      }); 
     }) 
    }, function(err) { 
     // Deal with an error 
     console.log("There was an error creating transaction : %s", err.detail); 
     res.send("something happened :O") 
    }); 
}) 
app.post('/successp', function (req, res) { 

    var token = req.body.stripeToken; // Using Express 
    // Charge the user's card: 
var charge = stripe.charges.create({ 
    amount: 1000, 
    currency: "eur", 
    description: "Example charge", 
    source: token, 
}, function(err, charge) { 
    // asynchronously called 
}); 
res.send('Thanks!') 
}) 
app.post('/successp', function (req, res) { 

    var token = req.body.stripeToken; // Using Express 
    // Charge the user's card: 
var charge = stripe.charges.create({ 
    amount: 1000, 
    currency: "eur", 
    description: "Example charge", 
    source: token, 
}, function(err, charge) { 
    // asynchronously called 
}); 
res.send('Thanks!') 
}) 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!') 
}) 

Мой HTML-форма:

<!DOCTYPE html> 
<html> 
<head> 
</head> 




<form action="https://ocelot-kgxujaijbj.now.sh/newship/" method="post"> 
    Company (Leave blank if you don't belong to one): <input type="text" name="company"><br> 
    First name: <input type="text" name="fnames"><br> 
    Last name: <input type="text" name="lnames"><br> 
    Street and Number: <input type="text" name="street"><br> 
    City: <input type="text" name="city"><br> 
    State: <input type="text" name="state"><br> 
    ZIP/PLZ: <input type="text" name="zipcode"><br> 
    Country (Please use the iso code, for example "US" for the USA or 'DE' for Germany): <input type="text" name="country"><br> 
    <input type="submit" value="Submit"> 
</form> 
</body> 
</html> 

Сервер действует, так что вы пытаетесь его самостоятельно. Спасибо заранее!

+0

Вы пробовали с помощью клиента HTTP, такие как Почтальон, чтобы попытаться отправить запрос к конечной точке за пределами вашего кода? –

+0

Нет, я сделаю это –

+0

Выполнено: не может POST/newship/(params here) @m_callens –

ответ

2

В коде, который вы там отправили, есть несколько вещей, которые не так. Кроме того, несмотря на то, что это тестовый токен, я настоятельно рекомендую вам отредактировать код, чтобы опустить его из сообщения.

Я внесла некоторые изменения в код, который вы предоставили, но у вас просто были некоторые ошибки, например, на addressFrom вам не хватало котировок около Mr. Shippotester. Кроме того, вы имели дополнительный ) где вы были res.status(200).send("Label can be found under: " + mpsTransaction.label_url);

Я настоятельно рекомендую Просмотрев Ваш server.js за любые ошибки (и я был бы удивлен его на самом деле работает).

var express = require('express') 
 
var app = express() 
 
var http = require('http'); 
 
//Shippo shipping wrapper 
 
var Raven = require('raven'); 
 
var shippo = require('shippo')('<YOUR API TEST TOKEN>'); 
 
const bodyParser = require('body-parser'); 
 
const path = require('path'); 
 
app.use(bodyParser.urlencoded({extended: true})); 
 
app.use(bodyParser.json()); 
 
app.use(express.static(path.join(__dirname, '/'))); 
 
//Test 
 

 
app.get('/', function (req, res) { 
 
    res.render('index.html'); 
 
}) 
 
app.post('/newship/', function (req, res) { 
 

 
    var addressFrom = { 
 
     "object_purpose":"PURCHASE", 
 
     "name": "Mr Shippotester", 
 
     "company":"Shippo", 
 
     "street1":"215 Clayton St.", 
 
     "city":"San Francisco", 
 
     "state":"CA", 
 
     "zip":"94117", 
 
     "country":"US", //iso2 country code 
 
     "phone":"+1 555 341 9393", 
 
     "email":"[email protected]", 
 
    }; 
 

 
    // example address_to object dict 
 
    var addressTo = { 
 
     "object_purpose":"PURCHASE", 
 
     "name": req.body.fnames + ' ' + req.body.lnames, 
 
     "company": req.body.company, 
 
     "street1":req.body.street, 
 
     "city":req.body.city, 
 
     "state":req.body.state, 
 
     "zip":req.body.zipcode, 
 
     "country": req.body.country, //iso2 country code 
 
     "phone":"+1 555 341 9393", 
 
     "email":"[email protected]", 
 
    }; 
 

 
    // parcel object dict 
 
    var parcelOne = { 
 
     "length":"5", 
 
     "width":"5", 
 
     "height":"5", 
 
     "distance_unit":"in", 
 
     "weight":"2", 
 
     "mass_unit":"lb" 
 
    }; 
 

 

 
    var shipment = { 
 
     "object_purpose": "PURCHASE", 
 
     "address_from": addressFrom, 
 
     "address_to": addressTo, 
 
     "parcel": [parcelOne], 
 
     "submission_type": "DROPOFF" 
 
    }; 
 

 
    shippo.transaction.create({ 
 
     "shipment": shipment, 
 
     "servicelevel_token": "dhl_express_domestic_express_doc", 
 
     "carrier_account": "9f123316d413417d9cc48627c402772c", 
 
     "label_file_type": "png" 
 
    }) 
 
    .then(function(transaction) { 
 
     shippo.transaction.list({ 
 
     "rate": transaction.rate 
 
     }) 
 
     .then(function(mpsTransactions) { 
 
      mpsTransactions.results.forEach(function(mpsTransaction){ 
 
       if(mpsTransaction.object_status == "SUCCESS") { 
 
        console.log("Label URL: %s", mpsTransaction.label_url); 
 
        console.log("Tracking Number: %s", mpsTransaction.tracking_number); 
 
        console.log("E-Mail: %s", mpsTransaction.object_owner); 
 
        console.log(mpsTransaction.object_status); 
 
        res.status(200).send("Label can be found under: " + mpsTransaction.label_url); 
 
       } else { 
 
        // hanlde error transactions 
 
        console.log("Message: %s", mpsTransactions.messages); 
 
       } 
 
      }); 
 
     }) 
 
    }, function(err) { 
 
     // Deal with an error 
 
     console.log("There was an error creating transaction : %s", err.detail); 
 
     res.send("something happened :O") 
 
    }); 
 
}) 
 
app.post('/successp', function (req, res) { 
 

 
    var token = req.body.stripeToken; // Using Express 
 
    // Charge the user's card: 
 
var charge = stripe.charges.create({ 
 
    amount: 1000, 
 
    currency: "eur", 
 
    description: "Example charge", 
 
    source: token, 
 
}, function(err, charge) { 
 
    // asynchronously called 
 
}); 
 
res.send('Thanks!') 
 
}) 
 
app.post('/successp', function (req, res) { 
 

 
    var token = req.body.stripeToken; // Using Express 
 
    // Charge the user's card: 
 
var charge = stripe.charges.create({ 
 
    amount: 1000, 
 
    currency: "eur", 
 
    description: "Example charge", 
 
    source: token, 
 
}, function(err, charge) { 
 
    // asynchronously called 
 
}); 
 
res.send('Thanks!') 
 
}) 
 

 
app.listen(3000, function() { 
 
    console.log('Example app listening on port 3000!') 
 
})
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
</head> 
 

 

 

 

 
<form action="http://localhost:3000/newship" method="post"> 
 
    Company (Leave blank if you don't belong to one): <input type="text" name="company"><br> 
 
    First name: <input type="text" name="fnames"><br> 
 
    Last name: <input type="text" name="lnames"><br> 
 
    Street and Number: <input type="text" name="street"><br> 
 
    City: <input type="text" name="city"><br> 
 
    State: <input type="text" name="state"><br> 
 
    ZIP/PLZ: <input type="text" name="zipcode"><br> 
 
    Country (Please use the iso code, for example "US" for the USA or 'DE' for Germany): <input type="text" name="country"><br> 
 
    <input type="submit" value="Submit"> 
 
</form> 
 
</body> 
 
</html>

+0

Спасибо! Теперь он работает безупречно! –

+0

Нет проблем! Кроме того, спасибо за удаление тестового токена из исходного сообщения. – mootrichard