【问题标题】:JS How to send http get request to my express server?JS如何向我的快递服务器发送http get请求?
【发布时间】:2019-03-30 23:38:06
【问题描述】:

我正在尝试向我用 js express 编写的简单服务器发送一个 http 获取请求,问题是我不知道我应该在 url 中输入什么来连接到将在本地运行的服务器。
第二个问题我如何从获取请求中获取价值? 在此示例中,“某物”值在请求中发送

服务器

const express = require('express');
const app = express();
const PORT = 4001;
app.get("/question",(req, res, next) => {
    res.send("something")
    console.log("got something")
})
app.listen(PORT, () =>{
    console.log("working")
})

客户

$(document).ready(function () {
    $('.item').on('click', (element) =>{
        $.get(??????/question)
    })
})

【问题讨论】:

  • 很可能是localhost:4001。您的本地计算机通常由 localhost 或 IP 127.0.0.1 引用
  • @Taplar 现在我收到了这样一个错误:CORS 策略已阻止从源“localhost:63342”访问“localhost:4001/cos”处的 XMLHttpRequest:跨源请求仅支持协议方案:http、数据、chrome、chrome-extension、https。我可以用这个做点什么吗?
  • @Taplar 我按照他们的建议做了(在前面添加了 http://),现在我收到了这样的错误:GET localhost:8080/some net::ERR_CONNECTION_REFUSED

标签: jquery express xmlhttprequest


【解决方案1】:

由于客户端不是 express 应用程序的一部分,并且假设您已运行开发模式。

http://localhost:4001/question

CORS 问题

您会遇到 cors,因为客户端不是 express 应用程序的一部分。

因此,您必须在您的 express 应用中包含以下代码。

const cors = require('cors'); // npm i -s cors - to install it in your express app
app.use(cors());

要过滤来源并做更多事情,请参考docs

【讨论】:

    猜你喜欢
    • 2017-01-28
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多