Setting up online payment

Need help creating a payment on the site, using paytrail.

I’m a little confused in reading the documentation and I can’t figure out how to do what seems to be such a simple task.

first I send a request to the server to get the hash and confirm my request to the paytrail server with it.

after I send a request from the frontend to the paytrail server to create an order.

how to implement request?

can you please give me a code example that would make it easier for me to understand how it should work.

documentation: https://docs.paytrail.com/#/?id=test-credentials

node.js – server:

const crypto = require('crypto');

const ACCOUNT = '375917';
const SECRET = 'SAIPPUAKAUPPIAS';

const calculateHmac = (secret, params, body) => {
const hmacPayload = Object.keys(params)
.sort()
.map((key) => [key, params[key]].join(':'))
.concat(body ? JSON.stringify(body) : '')
.join('n');

return crypto.createHmac('sha256', secret).update(hmacPayload).digest('hex');
};

const headers = {
'checkout-account': ACCOUNT,
'checkout-algorithm': 'sha256',
'checkout-method': 'POST',
'checkout-nonce': '564635208570151',
'checkout-timestamp': '2023-07-06T10:01:31.904Z',
};

const body = {
stamp: 'unique-identifier-for-merchant',
reference: '3759170',
amount: 1525,
currency: 'EUR',
language: 'FI',
items: [
{
unitPrice: 1525,
units: 1,
vatPercentage: 24,
productCode: '#1234',
deliveryDate: '2023-09-01',
},
],
customer: {
email: '[email protected]',
},
redirectUrls: {
success: 'http://localhost:8080/web/cart',
cancel: 'http://localhost:8080/web/cart',
},
};

const http = require("http");
const PORT = process.env.PORT || 3000;

const server = http.createServer(async (req, res) => {
res.end(JSON.stringify({
hash: await calculateHmac(SECRET, headers, body)
}));
});

server.listen(PORT, () => {
console.log(`server started on port: ${PORT}`);
});

fontend:

    <template>
<div>
<button @click="createPayment">create payment</button>
</div>
</template>

<script setup>
import axios from 'axios'

const createPayment = () => {
axios.post('https://services.paytrail.com/', {
orderNumber: '12345',
amount: 100.00,
currency: 'EUR',
locale: 'fi_FI',
returnUrl: 'https://project.su/web/',
cancelUrl: 'https://project.su/web/',
notificationUrl: 'https://project.su/web/'
}, {
headers: {
'Content-Type': 'application/json; charset=utf-8',
'checkout-account': '375917',
'checkout-algorithm': 'sha256',
'checkout-method': 'POST',
'checkout-nonce': 'server hash',
'checkout-timestamp': '2023-07-06T10:01:31.904Z',
},
})
.then(response => {

console.log(response.data);
})
.catch(error => {

console.error(error);
});
}
</script>

Failed to fetch at sendData (token.js:32:5) at HTMLButtonElement. (form.js:56:13)

I have a login form for an ecommerce website made with node + express which contains an email and a password input, when i press the submit button it gives me this “failed to fetch” error

Here’s the sendData function from token.js file

const sendData = (path, data) => {
    fetch(path, {
        method: 'post',
        headers: new Headers({'Content-Type': 'application/json'}),
        body: JSON.stringify(data)
    }).then((res) => res.json())
    .then(response => {
        processData(response);
    })
}

And here is the code from form.js (i have an if for the signup page and this else is for login page)

else {
        // login page
        if(!email.value.length || !password.value.length) {
            showAlert('fill all the inputs');
        } else {
            loader.style.display = 'block';
            sendData('/login', {
                email: email.value,
                password: password.value,
            })
        }
}

Also, my node server is not working, i expect it to type an email and a password from the database and to be redirected to the index.html page (main page). Can somebody help me please?

Sorting a Vuetify DataTable based on multiple field

In Vuetify 2.X it’s possible to use the custom-sort prop of VDataTable to implement a sort function that uses multiple fields to sort the rows. Here’s an example that sorts a table of people. When the name column is clicked the rows will be sorted by name alphabetically. People with the same name will be sorted in age order

<v-data-table :custom-sort="sortTableRows" :headers="headers" :items="people" />
export default {
  data() {
    const people = [
      {name: 'Bob', age: 25},
      {name: 'Ann', age: 25},
      {name: 'Bob', age: 21}
    ]
    const headers = [
      {text: 'Name', value: 'name'},
      {text: 'Age', value: 'age'}
    ]
    return {headers, people}
  },
  methods: {
    sortTableRows(items, sortBy, sortDesc, locale, customSorters) {
      if (sortBy[0] === 'name') {
        items.sort((row1, row2) => {
          const nameDiff = row1.name.toLowerCase().localeCompare(row2.name.toLowerCase())
          if (nameDiff === 0) {
            return row1.age - row2.age
          }
          return nameDiff
        })
        return items
      } else {
        // TODO implement sorting for age column
      }
    }
  }
}

In Vuetify 3.X the custom-sort prop has been replaced by custom-key-sort. However, this only provides access to the field that is being sorted, so there doesn’t seem to be any way to implement the sort function above in Vuetify 3.X. Here’s an example of using custom-key-sort to sort the names alphabetically

<v-data-table :custom-key-sort="customSorters" :headers="headers" :items="people" />
methods: {
  customSorters() {
    return {
      name: (name1, name2) => {
        const nameDiff = row1.name.toLowerCase().localeCompare(row2.name.toLowerCase())
        // AFAIK there's no way to access the age field here
        return nameDiff
      },
      age: (age1, age2) => { /* TODO implement sorting for age column */ }
    }
  }
}

Is it possible in Vuetify 3.X to implement a sort function that uses multiple fields to sort a VDataTable’s rows?

Use npm command in a repo that uses pnpm

I have a project that uses npm but I want to migrate to pnpm.
After pnpm import && rm package-lock.json && pnpm i --frozen-lockfile --shamefully-hoist everything installs smoothly, app runs, tests pass.
Is there any drawback / potential issue to still run everything (except the install, of course) e.g. npm run test, npm run build etc. with npm? Not seeing any problem currently.
Asking because changing the CI/CD pipelines would be quite some effort that I would like to postpone

React Google Map component not switching between 2D and 3D view after page refresh

React – Google Map component not able to switch from 2D to 3D after page refresh

I’m am trying to integrate google maps on 2d and 3d where the user can switch on either options. I have created a Parent Function with two onclick handlers one for 2D view and the other for 3D view. The onclick sets the state value to either true or false and the value is sent to the child function where google map is implemented. When I click on the onclick handlers the map switches from 2D to 3D as expected, but as soon as the page is refreshed, even though I can see the values passed across from the parent to the child to be correct, the map fails to switch until I comment out the streetViewPanorama and refresh the page and add it back again, before it works as expected. I’m not sure what I’m doing wrong.

Here is the parent page

function PropertyDetail(props) {

  const [state, setstate] = useState(false);

  const isEnabled = state;

return (     <article>
                <Box>
                  <h2>
                    Points of interest
                  </h2>
                  <Box>
                    <ul>
                      <li onClick={() => setstate(false)}>
                        Map
                      </li>
                      <li onClick={() => setstate(true)}>
                        3D
                      </li>
                    </ul>
                  </Box>
                  <Box>
                    <Box>
                      <PointOfInterest isEnabled={isEnabled} />
                    </Box>
                  </Box>
                </Box>
              </article>)

The child page

import { useMemo } from "react";
import {
  GoogleMap,
  MarkerF,
  StreetViewPanorama,
  useLoadScript,
} from "@react-google-maps/api";
import "./pointofinterest.css";

const PointOfInterst = (props) => {
  const { isLoaded } = useLoadScript({
    googleMapsApiKey: "xxxxxxxxxxxxx",
  });

  const center = useMemo(() => ({ lat: 7.4192661, lng: 3.8761708 }), []);

  return (
    <div className="App">
      {!isLoaded ? (
        <h1>Loading...</h1>
      ) : (
        <GoogleMap
          mapContainerClassName="map-container"
          center={center}
          zoom={17}
        >
          <StreetViewPanorama
            options={{ position: center, visible: props.isEnabled }}
          />
          <MarkerF position={{ lat: 7.4192661, lng: 3.8761708 }} />
        </GoogleMap>
      )}
    </div>
  );
};

export default PointOfInterst;

Even when the props.isEnabled is true the map doesn’t switch to the StreetViewPanorama after a page refresh.

React `StrictMode` does not allow message exchange between worker and React component

I am currently developing an application using webpack5 and React18.

I created the following code to exchange messages with webworker and React component which uses monaco-editor.

I expected app runs like following.

  • When button clicked, onSubmit() fires and send value to worker.

  • Worker get message with value, bundle it and send bundledCode back.

// React component
import React, { useState, useRef, useMemo, useEffect } from "react";
import * as monaco from 'monaco-editor';
import MonacoEditor from './Monaco/MonacoEditor';
import type { iMessageBundleWorker } from "../worker/types";

const MonacoContainer = (props) => {
    const [value, setValue] = useState<string>("");
    const bundleWorker = useMemo(
        () => new Worker(new URL('/src/worker/bundle.worker.ts', import.meta.url), { type: "module" }
        ), []
    );

    useEffect(() => {
        if(window.Worker) {
            bundleWorker.addEventListener('message', _cbBundledMessage, false);
        }

        return () => {
            _onUnmount();
        }
    }, []);

    const _onUnmount = () => {
        bundleWorker && bundleWorker.removeEventListener('message', _cbBundledMessage, false);
        bundleWorker && bundleWorker.terminate();
    };


    const _onSubmit = () => {

        console.log("Send code to worker");

        bundleWorker.postMessage({
            order: "bundle",
            code: value
        });
    };

    const _cbBundledMessage = (e: MessageEvent<iMessageBundleWorker>) => {
        bundledCode && console.log(bundledCode);
    };

    return (
        <div className="monaco-container">
            <MonacoEditor
              {/*...*/}
            />
            <button onClick={_onSubmit}>submit</button>
        </div>
    );
};
// worker
const bundler = (code: string) => {
    // bundle code and return it.
};

self.addEventListener('message', (e:MessageEvent<iMessageBundleWorker>): void => {

    const { order, code } = e.data;


    console.log("[bundle.worker.ts] got message");

    if(order !== "bundle") return;

    console.log("[bundle.worker.ts] start bundle process...");

    if(code) {
        bundler(code)
        .then((result: iBuildResult) => {
            self.postMessage({
                bundledCode: result.code,
                err: null
            });
        })
        .catch((e) => {
            // handle error
        });
    }
}, false);


console.log("[bundle.worker] running...");
// parent component
import React from 'react';

const App = () => {
    return (
        <div>
            <React.StrictMode>
                <MonacoContainer />
            </React.StrictMode>
        </div>
    )
}

When I run it, I can see that no messages are being exchanged.

However, if I remove StrictMode, it immediately exchanges message without problems.

But with StrictMode, it won’t.

Here is what I have surveyed to solve.

  • StrictMode causes useEffect() to be ran twice, so maybe not cleaning up properly has something to do with this problem?

Both worker.terminate() and worker.removeEventListener('message') are executed during cleanup.

  • Is it because they have different origins?

Development is done locally, and I have confirmed that both are http://localhost:8080.
So it should not be cross-origin.

  • You think I am missing the message because the React component and the worker have different timing for completion of mounting.

I don’t think that is related to StrictMode, as it does not occur when app runs without StrictMode.

So I’m stuck.

Is there any limitation to communicate with a worker in React18 that cannot be done in development mode?

I am developing in Strictmode with React18, webpack5, but I wonder if there is any way to exchange messages with the worker without any problems.

My environment and settings.

Node.js version 16

// tsconfig.json
{
  "compilerOptions": {
    "target": "es2016",
    "lib": ["dom", "WebWorker", "es5", "es2015.collection", "es2015.promise"],
    "jsx": "react",
    "module": "ES2020",
    "moduleResolution": "node",
    "typeRoots": ["node_modules/@types"],
    "resolveJsonModule": true,
    "allowJs": true,
    "sourceMap": true,
    "outDir": "./dist/",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "skipLibCheck": true
  },
  "include": ["./src/**/*"],
  "exclude": ["node_modules"]
}
// webpack.config.js
const path = require('path');
const HtmlWebPackahePlugin = require('html-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

const isDevelopment = process.env.NODE_ENV !== 'producton';

module.exports = {
    mode: 'development',
    entry: {
        index: './src/index.tsx',
        'bundle.worker': './src/worker/bundle.worker.ts',

        // monaco-editor requirement:
        'editor.worker': 'monaco-editor/esm/vs/editor/editor.worker.js',
        'json.worker': 'monaco-editor/esm/vs/language/json/json.worker',
        'css.worker': 'monaco-editor/esm/vs/language/css/css.worker',
        'html.worker': 'monaco-editor/esm/vs/language/html/html.worker',
        'ts.worker': 'monaco-editor/esm/vs/language/typescript/ts.worker'
    },
    resolve: {
        extensions: ['.*', '.js', '.jsx', '.tsx', '.ts'],
      },
    output: {
        globalObject: 'self',
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        clean: true,
    },
    module: {
        rules: [
            {
                test: /.(js|jsx|tsx|ts)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: require.resolve('babel-loader'),
                        options: {
                            presets: ['@babel/preset-env', '@babel/preset-typescript', '@babel/preset-react'],
                            plugins: [isDevelopment && require.resolve('react-refresh/babel')].filter(Boolean)
                        }
                    }
                ]
            },
            {
                test: /.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /.ttf$/,
                use: ['file-loader']
            }
        ]
    },
    plugins: [
        new HtmlWebPackahePlugin({
            title: 'Output Management',
            template: 'src/index.html'
        }),
        isDevelopment && new ReactRefreshWebpackPlugin()
    ].filter(Boolean),
    devtool: 'inline-source-map',
    devServer: {
        static: './dist',
        hot: true,
        port: 8080,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': '*',
            'Access-Control-Allow-Methods': '*',
        }
    },
    optimization: {
        runtimeChunk: 'single'
    }
};

Thank you.

How can I send fetch api requests if an html element is rendered on the page?

I am building a vanilla JS single page application (project requirement) and I change the pages using the following code

const routes = {
  "/src/main/webapp/": "/pages/courses.html",
  "/src/main/webapp/create-course": "/pages/create-course.html",
  "/src/main/webapp/about": "/pages/about.html",
};

const handleLocation = async () => {
  const path = window.location.pathname;
  console.log(path);
  const route = routes[path] || routes[404];
  const html = await fetch(prefix + route).then((data) => data.text());
  document.getElementById("main-page").innerHTML = html;
  handleChange();
};

window.onpopstate = handleLocation;

Which depending on the current url inserts predefined html pages inside of the the <div id="main-page"></div> element. I want to send certain fetch api requests when each page loads. For example, when the about page loads (“/src/main/webapp/about”), I want js to send requests to retrieve “about” information and render it on the page, how may I detect that certain elements appear on the page and when they load send requests?

I tried event listeners but they did not work

Javascript Nullish Coalescing behavior [duplicate]

The following Nullish Coalescing is not working as I would expect and do not understand why;

const baz = 3 ?? 4 === 5 ? 1 : 2;
console.log(baz); // this returns 1

I would expect this expression to return 3 and do not understand why it is returning 1

How I translate this expression to English:

If 3 is not null/undefined,
then compare 4 == 5,
if 4 == 5 is true then return 1,
else return 2

Because of that I would expect this expression to return 3. Why is it returning 1?

A is only ever to be used as the child of element, never rendered directly after migration to latest dependencies

I want to migrate old React project to latest dependencies but I get this issue:

Old code:

const NonPrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    getCurrentUser() ? (
      <Redirect to={{
        pathname: "/auth",
        state: { from: props.location }
      }} />
    ) : (
        <Component {...props} />
      )
  )} />
)

New:

const NonPrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    getCurrentUser() ? (
      <Navigate to={{
        pathname: "/auth",
        state: { from: props.location }
      }} />
    ) : (
        <Component {...props} />
      )
  )} />
)

But I get error: Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Full code: https://github.com/rcbandit111/spring_security_6_gateway_hardening/blob/main/keycloak-oidc-reactjs-client/src/App.js

Do you know how I can fix this issue?

Corrupted file display after uploading to Firebase Storage using JavaScript and React

I’m currently working on a React application where users can upload images to Firebase Storage. The file upload process seems to be working fine, but when I try to display the uploaded image, it appears to be corrupted. I’m seeking assistance in understanding what might be causing this issue and how to resolve it.

Here’s an overview of my code and the steps I’m taking:

I have a form where users can select an image file using an element.
When the form is submitted, I handle the file upload in the handleSubmit function.
Here’s an excerpt of the relevant code:

//metadata declaration during initialisation
 const metadata = {
    contentType: 'image/png',
  };

// Inside the handleSubmit function
const file = fileInputRef.current; // Retrieves the file from the file input element
const fileName = "MYFILENAME"; // Constructs a unique file name in code
const storageRef = ref(storage, `${fileName}.png`); 
const uploadTask = uploadBytesResumable(storageRef, file, metadata);

uploadTask.on(
  (error) => {
    // Handle error
  },
  (snapshot) => {
    // Progress event listener: called periodically to track the upload progress
      getDownloadURL(snapshot.ref) // Retrieves the download URL of the uploaded file
        .then((downloadURL) => {
          console.log("File available at", downloadURL); // the download URL routes to a corrupt document 
          updateDoc(docRef, { displayURL: downloadURL }) // Updates the user document in Firestore with the download URL
            .then(() => {
              console.log("File uploaded successfully"); // success message to the console is always received 
            })
            .catch((error) => {
                  // Handle error
            });
  }
);

The file does get uploaded to Firebase Storage successfully, but when I try to display it by setting the src attribute of an tag to the download URL, the image appears corrupted or broken. I’ve also noticed that when I try to view the image directly from Firebase Storage, I encounter the same issue.

I’ve ensured that the file being uploaded is a valid PNG image and that the content type is set correctly in the metadata object. I’m not sure what could be causing the corruption during the upload process or when retrieving the file for display.

Has anyone experienced a similar issue or have any suggestions on what could be causing this problem? I would greatly appreciate any insights or guidance on how to troubleshoot and resolve this issue.

Bootstrap tooltip is flickering, doesn’t close on mouseout, duplicate entries are not triggered?

I have the following code: https://jsfiddle.net/ov7qhmkt/

The problems:

  1. Flickering – Try to hover with your mouse slowly over the images, you will notice that sometimes it flickers/renders the tooltip box 2-3 times. Seems to be related to the class="me-1" that adds a small margin-right to the images in the each() function when you move your mouse from right to left on the images.
  2. Doesn’t close on mouseout – Try to hover over all of the images faster, you will notice that the tooltip boxes are still open even though the mouse is not hovering over them.
  3. Duplicate entries not rendering – As you can see, the third and fourth rows are identical. Try to hover over the first row one by one, it will render correctly. Now hover over the fourth row, you will notice that the tooltip is not rendering at all for them.

I have played with the code but nothing seems to be solving the issues I’m having. I tried something like this without any luck:

$(".hover-tooltip").mouseleave(function(){
    const tooltipEl = bootstrap.Tooltip.getInstance($(this));
    tooltipEl.hide();
});

Could someone point me in the right direction please?

Parent variable in Vue 3 not updated when using update-emit on prop

I’ve the following very simple Vue 3 component:

<template lang="pug">
b-modal(v-model="dshow")
  template(v-slot:default) test
</template>

<script>
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dshow: false
    }
  },
  watch: {
    show: function () {
      this.dshow = this.show
    },
    dshow: function () {
      this.$emit('update:show', this.dshow)
    }
  }
}
</script>

In my parent component, I’m using this as following:

import demo from 'mymodal.vue'

<template lang="pug">
button.btn.btn-primary.hstack.gap-2(@click="showModal= true") Show Modal!
demo(:show.sync="showModal")
</template>

<script>
export default {
  components: {
    demo
  },
  data() {
    return {
      showModal: false
    }
  }
}
</script>

Now, when I click on my button in the parent, the modal appears and when I close / hide the dialog, the callback for my watched variable dshow is also called. But unfortunately, my parent component isn’t informed about the update. So when I click on my button next time, nothing happens, because the showModal hasn’t been updated. this.$emit('update:show', this.dshow) is emitted, but the parent value isn’t updated.

Any idea on this? I run completely out of ideas on this 🙁

Getting ‘Undefined symbol for architecture arm64’ error after switching from react-native-webview to react-native-wkwebview-reborn on iOS

I have an app on React Native and I am using Windows OS. I built this app and when I tried to submit (with EAS) I got email from Apple with the thext below:

ITMS-90809: Deprecated API Usage – New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security and reliability. Learn more (https://developer.apple.com/documentation/uikit/uiwebview).
The app is old and I am working on updates. It had WebView from react-native-webview, I changed the component to WKWebView and react-native-wkwebview-reborn.

And now I am getting this error:


❌  Undefined symbols for architecture arm64
┌─ Symbol: _RCTJSNavigationScheme
└─ Referenced from: -[CRAWKWebView webView:decidePolicyForNavigationAction:decisionHandler:] in libreact-native-wkwebview.a(CRAWKWebView.o)
1040

❌  ld: symbol(s) not found for architecture arm64


❌  clang: error: linker command failed with exit code 1 (use -v to see invocation)


▸ ** ARCHIVE FAILED **

▸ The following build commands failed:

▸     Ld /Users/expo/Library/Developer/Xcode/DerivedData/ProjectName-gnavtiawokiilkhfsvxzptupfwxa/Build/Intermediates.noindex/ArchiveIntermediates/ProjectName/InstallationBuildProductsLocation/Applications/ProjectName.app/ProjectNamenormal (in target 'ProjectName' from project 'ProjectName')

▸ (1 failure)

** ARCHIVE FAILED **

The following build commands failed:

    Ld /Users/expo/Library/Developer/Xcode/DerivedData/ProjectName-gnavtiawokiilkhfsvxzptupfwxa/Build/Intermediates.noindex/ArchiveIntermediates/ProjectName/InstallationBuildProductsLocation/Applications/ProjectName.app/ProjectNamenormal (in target 'ProjectName' from project 'ProjectName')

(1 failure)

Exit status: 65

+-------------+-------------------------+

|           Build environment           |

+-------------+-------------------------+

| xcode_path  | /Applications/Xcode.app |

| gym_version | 2.211.0                 |

| sdk         | iPhoneOS16.2.sdk        |

+-------------+-------------------------+

Looks like fastlane ran into a build/archive error with your project

It's hard to tell what's causing the error, so we wrote some guides on how

to troubleshoot build and signing issues: https://docs.fastlane.tools/codesigning/getting-started/

Before submitting an issue on GitHub, please follow the guide above and make

sure your project is set up correctly.

fastlane uses `xcodebuild` commands to generate your binary, you can see the

the full commands printed out in yellow in the above log.

Make sure to inspect the output above, as usually you'll find more error information there

[stderr] 
[!] Error building the application - see the log above

Error: The "Run fastlane" step failed with an unknown error. Refer to "Xc

I have tried npx react-native-assets with react-native.config.js:

    module.exports = {
    project: {
        ios: {}
        },
    assets: ['./node_modules/react-native-wkwebview-       reborn/ios/RCTWKWebView.xcodeproj/project.pbxproj'],
    };

Also tried this:

    NSString *const RCTJSNavigationScheme = @"react-js-navigation";

I am not sure that I have tried these methods correctly, but anyways.

How do I adjust my JS to account for the last days of the previous month?

I want to show “The last days of the offer” for example:

Offer days: 1, 2 and 3 of June 2023.

My code works fine, until I get to the start of a new month.

At the beginning of each month, it shows like this:

0, 1 and 2 of June 2023 but it should be 31, 1 and 2 of June 2023.

That is, I need to show the last day of the previous month instead of 0.

Or the last two days of the month, in this example: 30, 31 and 1 of June 2023.

PS: The date format may look wrong for English speakers, because it is in Portuguese format.

PPS: Usually I have to use it in more than one place on the same page.

PPPS: Sorry for the poor code, I’m learning.

<span id="diaspromocao1"></span>
<span id="diaspromocao2"></span>

Sorry for the poor code, I’m learning.

<script type="text/javascript">
var months = new Array(12);
months[0] = "Janeiro";
months[1] = "Fevereiro";
months[2] = "Março";
months[3] = "April";
months[4] = "Maio";
months[5] = "Junho";
months[6] = "Julho";
months[7] = "Augosto";
months[8] = "Setembro";
months[9] = "Outobro";
months[10] = "Novembro";
months[11] = "Dezembro";

var current_date = new Date();
current_date.setDate(current_date.getDate() + 0);
month_value = current_date.getMonth();
day_value = current_date.getDate();
day_value1 = current_date.getDate() - 1;
day_value2 = current_date.getDate() - 2;                                        
year_value = current_date.getFullYear();

document.getElementById("diaspromocao1").innerHTML = + day_value2 + ", " + day_value1 + " e " + day_value + " de "+ months[month_value] + " de " + year_value;
document.getElementById("diaspromocao2").innerHTML = + day_value2 + ", " + day_value1 + " e " + day_value + " de "+ months[month_value] + " de " + year_value;

</script>

I don’t know what else to do to resolve this. Would anyone here be able to help me out? Thank you!