javascript - Unable to get data from different origin/host JQuery Nodejs-Express
问题描述
I am trying to fetch simple data from a different host using JQuery Ajax request. Here is the example to reproduce:
Node.js express server file server.js
:
var express = require('express');
var app = express();
var path = require('path');
// var cors = require('cors')
// app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
})
app.get('/', function(req, res) {
console.log(res.getHeaders());
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(3000, function name(params) {
console.log(`App listening on port 3000`);
});
This is the html file index.html
:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
console.log(`Request start`);
$.ajax({
type: "GET",
url: "https://csrhub.com/number/",
crossDomain: true,
success: function(data, status) {
console.log(data);
alert("Thanks!");
},
error: function(jqXhr, textStatus, errorMessage) {
console.log(textStatus);
console.log(errorMessage);
}
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
And upon file-load in Chrome I get this errors:
Console: And here are the headers from the resource fetch:
The message is descriptive, but is this cros-origin-request really so uncommon? I mean it should be allowed frontend to request APIs for example.Can I make this work without chrome extensions workaround? I need this functionality in production. How to make this work?
EDIT Guys, did you read the answer my question is suggested to be duplicate of? This is not a duplicate. I am an owner of the server. I put the necessary headers. I also installed https://www.npmjs.com/package/cors and tried again. Same situation! I read the original question. The question and the context are not the same. This is not a duplicate. Why is this closed? I applied the necessary headers that allow CORS. It still doesnt work. Why?
Changed the code according to suggestions by @Joodjindy
Here is some more real time example https://youtu.be/ROWfnwBtQYE
解决方案
推荐阅读
- sql - 如何在 Oracle 中获取逗号分隔字符串的最大 COUNT?
- python - 如何使用带有 python2.7 的 Pyodbc 在数据库中插入 unicode 字符串
- vue-component - Vue.js我如何循环抛出一个数组以根据数组项将组件添加到dom
- sql-server - 如何从本地 SQL Server 2016 迁移到 Azure SQL Hyperscale
- mips - 了解字符串如何存储在 MIPS 中以及如何计算字符串中的字符数
- reactjs - 在 reactjs 中集成条带支付网关时出现 cors 问题
- pentaho - Pentaho 不会注册我的插件:注册 jar 插件时出现意外错误
- ssl - Wso2 Ei 6.3 自签名认证错误
- python - 如何从熊猫系列中的字符串中去除“$”符号?
- python-3.7 - ValueError:无法将字符串转换为浮点数:'ill afb'