REST url返回错误或无法连接

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了REST url返回错误或无法连接相关的知识,希望对你有一定的参考价值。

我正在尝试从MongoDB Atlas集群中获取数据。这在localhost上运行良好,但是在Google Cloud上尝试使用时,发送用于获取产品的URL失败。

URL的格式如下:

import DataTypes from "./Types";

const protocol = "https";
// const hostname = "localhost"; <- this here works on localhost
const hostname = "ugo-dapashirts.appspot.com";
const port = process.env.PORT || 9090;

export const RestUrls = 
    [DataTypes.PRODUCTS]: `$protocol://$hostname:$port/products`,
    [DataTypes.CATEGORIES]: `$protocol://$hostname:$port/categories`,
    [DataTypes.ORDERS]: `$protocol://$hostname:$port/orders`

这是我的server.js文件:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const port = process.env.PORT || 9090

const app = express();

app.use(cors());
app.use(bodyParser.urlencoded(extended:true));
app.use(bodyParser.json());

// Configuring the database
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

// Connecting to the database
mongoose.connect(dbConfig.url, 
    useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true
).then(() => 
    console.log("Successfully connected to the database");    
).catch(err => 
    console.log('Could not connect to the database. Exiting now...', err);
    process.exit();
);

// Require routes
require('./routes/department.routes.js')(app);
require('./routes/category.routes.js')(app);
require('./routes/product.routes.js')(app);
require('./routes/order.routes.js')(app);

app.listen(port, () => 
    console.log("Server is listening on port 9090");
);

这里是示例路由文件:

module.exports = (app) => 
    const products = require('../controllers/product.controllers.js');

    // Create a new product
    app.post('/api/products', products.create);

    // Retrieve all products
    app.get('/api/products', products.findAll);

    // Retrieve a single product with productId
    app.get('/api/products/:productId', products.findOne);

    // Retrieve a products with categoryId
    app.get('/api/products/:categoryId', products.findWithCategoryId);

    // Update a product with productId
    app.put('/api/products/:productId', products.update);

    // Delete a produt with productId
    app.delete('/api/products/:productId', products.delete);

和示例控制器文件:

const Product = require('../models/product.model.js');

// Create and Save a new Product
exports.create = (req, res) => 
    // Validate request
    if (!req.body.categoryId) 
        return res.status(400).send(
            error: "categoryId cannot be empty"
        );
    
    else if (!req.body.name) 
        return res.status(400).send(
            error: "Product name cannot be empty"
        );
    
    else if (!req.body.description) 
        return res.status(400).send(
            error: "Product description cannot be empty"
        );
    

    // Create a Product
    const product = new Product(
        category_id: req.body.categoryId,
        name: req.body.name, 
        description: req.body.description,
        price: Number(req.body.price).toFixed(2),
        discounted_price: Number(req.body.discountedPrice).toFixed(2),
        image: req.body.image,
        image_2: req.body.image_2,
        thumbnail: req.body.thumbnail,
        display: Number(req.body.display)
    );

    // Save Product in the database
    product.save()
    .then(data => 
        res.send(data);
    ).catch(err => 
        res.status(500).send(
            error: err.message || "Some error occurred while creating the Product."
        );
    );
;

// Retrieve and return all products from the database.
exports.findAll = (req, res) => 
    Product.find()
    .then(product => 
        res.send(product);
    ).catch(err => 
        res.status(500).send(
            error: err.message || "Some error occurred while retrieving products."
        );
    );
;

// Find a single product with a productId
exports.findOne = (req, res) => 
    Product.findById(req.params.productId)
    .then(product => 
        if(!product) 
            return res.status(404).send(
                error: "Product not found with id " + req.params.productId
            );            
        
        res.send(product);
    ).catch(err => 
        if(err.kind === 'ObjectId') 
            return res.status(404).send(
                error: "Product not found with id " + req.params.productId
            );                
        
        return res.status(500).send(
            error: "Error retrieving product with id " + req.params.productId
        );
    );
;

// find product with categoryId
exports.findWithCategoryId =(req, res) => 
    Product.find(category_id: req.params.categoryId)
    .then(product => 
        if(product.length) 
            return res.status(404).send(
                error: "Product not found with categoryId " + req.params.categoryId
            );            
        
        res.send(product);
    ).catch(err => 
        if(err.kind === 'ObjectId') 
            return res.status(404).send(
                error: "Product not found with categoryId " + req.params.categoryId
            );                
        
        return res.status(500).send(
            error: "Error retrieving product with categoryId " + req.params.categoryId
        );
    );
;

// Update a product identified by the productId in the request
exports.update = (req, res) => 
    // Validate Request
    if (!req.body.categoryId) 
        return res.status(400).send(
            error: "categoryId cannot be empty"
        );
    
    else if(!req.body.name) 
        return res.status(400).send(
            error: "Product name cannot be empty"
        );
    
    else if (!req.body.description) 
        return res.status(400).send(
            error: "Product description cannot be empty"
        );
    

    // Find Product and update it with the request body
    Product.findByIdAndUpdate(req.params.productId, 
        category_id: req.body.categoryId,
        name: req.body.name, 
        description: req.body.description,
        price: Number(req.body.price).toFixed(2),
        discounted_price: Number(req.body.discountedPrice).toFixed(2),
        image: req.body.image,
        image_2: req.body.image_2,
        thumbnail: req.body.thumbnail,
        display: Number(req.body.display)
    , new: true)
    .then(prod => 
        if(!prod) 
            return res.status(404).send(
                error: "Product not found with id " + req.params.productId
            );
        
        res.send(prod);
    ).catch(err => 
        if(err.kind === 'ObjectId') 
            return res.status(404).send(
                error: "Product not found with id " + req.params.productId
            );                
        
        return res.status(500).send(
            error: "Error updating product with id " + req.params.productId
        );
    );
;

// Delete a product with the specified productId in the request
exports.delete = (req, res) => 
    Product.findByIdAndRemove(req.params.productId)
    .then(prod => 
        if(!prod) 
            return res.status(404).send(
                error: "Product not found with id " + req.params.productId
            );
        
        res.send(message: "Product deleted successfully!");
    ).catch(err => 
        if(err.kind === 'ObjectId' || err.name === 'NotFound') 
            return res.status(404).send(
                error: "Product not found with id " + req.params.productId
            );                
        
        return res.status(500).send(
            error: "Could not delete product with id " + req.params.productId
        );
    );
;

这是我的app.yaml

runtime: nodejs10
handlers: 
- url: /api/.*
  script: auto
- url: /(.*\..+)$
  static_files: build/\1
  upload: build/(.*\..+)$
- url: /.*
  static_files: build/index.html
  upload: build/index.html

端口有问题吗?我真的很困惑,GCP有时很烂

答案

根据Node.js的GAE documentation配置上的app.yaml,您的服务器必须在端口8080上接受请求(您的端口设置为9090)。

摘自文档(重点是我的文档):

入口点 |可选的。当应用启动时,通过执行entrypoint命令来覆盖默认的启动行为。为了使您的应用程序能够接收HTTP请求,entrypoint元素应包含一个命令,该命令将启动侦听端口8080的Web服务器。如果您未指定入口点,则App Engine将使用在[[package.json文件中指定的启动脚本。

以上是关于REST url返回错误或无法连接的主要内容,如果未能解决你的问题,请参考以下文章

Python无法通过以下方式连接Jira API

错误:您所请求的网址(URL)无法获取 怎么搞的?

使用 REST 接口连接到数据库:无法连接

60+% 的请求给出 curl 错误 URL 错误 7: 无法连接

Team Foundation Server 突然无法连接(错误:TF400324)

Java使用JDBC连接Hive