简体   繁体   English

向外部发出请求 api

[英]make a request to an external api

i am learning node.js and i have a problem.我正在学习 node.js,我遇到了问题。 basically I'm trying to create an api route that will make a call to an external api基本上我正在尝试创建一个 api 路由,它将调用外部 api

but when I do a test with postman, I get the error "Cannot GET /api/books".但是当我用 postman 进行测试时,我收到错误“无法获取/api/books”。 has anyone have an idea?有没有人有想法?

here is my function. (for security reasons I did not add my APIkey in the post这是我的 function。(出于安全原因,我没有在帖子中添加我的 APIkey

 const pool = require("../db"); const fetch = require('node-fetch'); exports.getOneBooksbyName = (req, res, next) => { const title = req.params; const APIKey = ""; fetch("https://www.googleapis.com/books/v1/volumes?q=" +title+ "&key="+APIKey).then(res => { const data = res.json(); res.status(200).json(data); } ).catch(err =>{ res.status(500).json({message:'error'}) }) };

and then my route然后是我的路线

 const express = require('express'); const router = express.Router(); const {getOneBooksbyName} = require('../controllers/books'); router.get('/?title', getOneBooksbyName); module.exports = router;

and finally my app.js最后是我的 app.js

 const express = require("express"); const pool = require("./db.js") const UserRoutes = require("./routes/user.js"); const app = express(); var bodyParser = require('body-parser'); const BookRoutes = require("./routes/book.js"); app.use(express.json()); //pour gerer les requetes POST app.use(bodyParser.urlencoded({ extended: true })); app.use((req,res,next)=>{// POUR CONTOUNER LA SECURITE CORS res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS'); next(); }); app.use('/api/users', UserRoutes); app.use('/api/books', BookRoutes); module.exports = app;

I use java script and jquery to achieve this我使用 java 脚本和 jquery 来实现这个

Javascript function using jquery ajax to call API via URL and return result Javascript function 使用 jquery ajax 通过 URL 调用 API 并返回结果

function api_fetch(url) {
    var result = 0;
    $.ajax({
        url:url,
        type: 'GET',
        async: false,
        dataType: 'html',
        success: function (response) {
            console.log(`response from fetch ${response}`)
            result =  response
        },
        error: function (error)
        {
            console.log(`response from fetch ${error}`)
            result = error
        }
    })

    return result
}

I personally created a Django API, and I need to check if there is a record for a number in a database, so I implemented another js function to call the API我自己创建了一个Django API,需要查询一个号码在数据库中有没有记录,所以又实现了一个js function来调用API

function check_number(number) {
    let get = api_fetch(`/api/verifnum/${number}`)
    console.log(`check number fetch ${get}`)
}

when I console log check number it gives me desired result当我控制日志检查编号时,它给了我想要的结果

check_number('number') // returns number of record if exist or 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM