Полный исходный код JSONP с использованием NodeJS, Express и JavaScript. JSONP и сервер, ответ которого представляет собой вызов функции. Цитата из w3schools «JSONP — это метод для отправки данных JSON, не беспокоясь о проблемах кросс-домена.». Вот ссылка https://www.w3schools.com/js/js_json_jsonp.asp.
Это меня заинтересовало, и я захотел сделать это с помощью JavaScript.
JSONP
Нам понадобятся:
Клиент со скриптом:
<script src="/jsonp-static"></script>
Сервер с маршрутом:
const app = require('express')();
app.get('/jsonp-static', (req, res) => {
res.send(`jsonp({ data: 'data' })`);
});
Что происходит?
Сценарий, нацеленный на запрос, который возвращает строку, являющуюся вызовом функции, пытается вызвать эту функцию на клиенте.
Если эта функция не существует на клиенте, мы получаем ошибку ссылки.
Получается, что мы «вызываем» клиентскую функцию с сервера. Этот вызов происходит, когда сценарий указывает на запрос, который возвращает строкоподобный вызов функции.
Возврат кода JavaScript с сервера
Код — это всего лишь текст. Мы можем передавать его как угодно. Как только скрипт получает код, он пытается его выполнить.
app.get('/js-code', (req, res) => {
res.send(`
console.log(
'Hi there! A script <script src="js-code"></script> will run me'
);
function iCanDoAnything() {
// i can add an element
const body = document.getElementsByTagName('body')[0];
const h1 = document.createElement('h1');
h1.innerText = 'Daayum! I really can do anything.';
body.appendChild(h1);
}
iCanDoAnything();
`);
});
Полный исходный код
Полный исходный код JSONP с использованием NodeJS, Express, JavaScript.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
/>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>JSONP Client</title>
</head>
<body>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- NOTE! -->
<!-- TO RUN THE EXAMPLE, PLACE THIS FILE IN 'public' DIRECTORY!!! -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- The definition of a function that our server calls. -->
<script>
// Try commenting out the function
// The script with src="jsonp-static" throws ReferenceError jsonp
function jsonp(data) {
console.log(data);
}
</script>
<!-- Request a server to call our function with the data. -->
<script src="jsonp-static"></script>
<!-- Inspect the server response. -->
<script>
// SyntaxError
// JSON.parse: unexpected character at line 1 column 1 of the JSON data
fetch('jsonp-static')
.then((res) => res.json())
.then(console.log)
.catch(console.error);
// Read raw response from the stream because res.json() throws an error
fetch('jsonp-static')
.then((res) => res.body.getReader())
.then((reader) => {
let res = '';
let decoder = new TextDecoder();
// Parse data from the stream
return reader.read().then(function readStream({ value, done }) {
res += decoder.decode(value);
// Keep reading data until we are done, then return data
if (done) return res;
else return reader.read().then(readStream);
});
})
.then(console.log)
.catch(console.error);
</script>
<!-- The code received from the server should run. -->
<script src="js-code"></script>
</body>
</html>
server.js
const express = require('express');
const { join } = require('path');
const app = express();
// NOTE!!!
// This is a gist, we can't use directories here.
// Make sure to place index.html in the 'public' directory.
app.use(express.static('public'));
app.get('/jsonp-static', (req, res) => {
res.send(`jsonp({ foo: 'foo' })`);
});
app.get('/js-code', (req, res) => {
res.send(`
console.log(
'Hi there! A script <script src="js-code"></script> will run me'
);
function iCanDoAnything() {
// i can add an element
const body = document.getElementsByTagName('body')[0];
const h1 = document.createElement('h1');
h1.innerText = 'Daayum! I really can do anything.';
body.appendChild(h1);
}
iCanDoAnything();
`);
});
app.listen(3000, () => console.log('server: http://localhost:3000'));
package.json
{
"version": "0.1.0",
"name": "jsonp",
"description": "Send data using html script tags",
"author": "Kostic Srecko",
"repository": {
"type": "git",
"url": "git+https://github.com/srele96/sk-experiments.git"
},
"bugs": {
"url": "https://github.com/srele96/sk-experiments/issues"
},
"scripts": {
"start": "nodemon server"
},
"dependencies": {
"express": "^4.18.1"
},
"devDependencies": {
"nodemon": "^2.0.18"
}
}
Ссылки
- https://gist.github.com/srele96/a512f155218cf7e9482ad7d3cc673b63
- https://gist.github.com/srele96/40505f053bdd9ce45701cfe1dd74e9e7
- https://gist.github.com/srele96/3441d42c1380ea0f161d54fa730bb2a8
- https://gist.github.com/srele96/c5fd139d87960b4f7a884e046aebe994
Больше экспериментов в моем репозитории GitHub
- https://github.com/srele96/sk-experiments